001/** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, software 014 * distributed under the License is distributed on an "AS IS" BASIS, 015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 016 * See the License for the specific language governing permissions and 017 * limitations under the License. 018 */ 019package org.apache.hadoop.hbase.client; 020 021import java.io.IOException; 022import java.util.ArrayList; 023import java.util.Arrays; 024import java.util.Collection; 025import java.util.Collections; 026import java.util.HashMap; 027import java.util.HashSet; 028import java.util.List; 029import java.util.Map; 030import java.util.Objects; 031import java.util.Optional; 032import java.util.Set; 033import java.util.TreeMap; 034import java.util.TreeSet; 035import java.util.function.Function; 036import java.util.regex.Matcher; 037import java.util.regex.Pattern; 038import org.apache.hadoop.fs.Path; 039import org.apache.hadoop.hbase.Coprocessor; 040import org.apache.hadoop.hbase.HConstants; 041import org.apache.hadoop.hbase.TableName; 042import org.apache.hadoop.hbase.exceptions.DeserializationException; 043import org.apache.hadoop.hbase.security.User; 044import org.apache.hadoop.hbase.util.Bytes; 045import org.apache.yetus.audience.InterfaceAudience; 046import org.slf4j.Logger; 047import org.slf4j.LoggerFactory; 048 049import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil; 050import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos; 051 052/** 053 * @since 2.0.0 054 */ 055@InterfaceAudience.Public 056public class TableDescriptorBuilder { 057 public static final Logger LOG = LoggerFactory.getLogger(TableDescriptorBuilder.class); 058 @InterfaceAudience.Private 059 public static final String SPLIT_POLICY = "SPLIT_POLICY"; 060 private static final Bytes SPLIT_POLICY_KEY = new Bytes(Bytes.toBytes(SPLIT_POLICY)); 061 /** 062 * Used by HBase Shell interface to access this metadata 063 * attribute which denotes the maximum size of the store file after which a 064 * region split occurs. 065 */ 066 @InterfaceAudience.Private 067 public static final String MAX_FILESIZE = "MAX_FILESIZE"; 068 private static final Bytes MAX_FILESIZE_KEY 069 = new Bytes(Bytes.toBytes(MAX_FILESIZE)); 070 071 @InterfaceAudience.Private 072 public static final String OWNER = "OWNER"; 073 @InterfaceAudience.Private 074 public static final Bytes OWNER_KEY 075 = new Bytes(Bytes.toBytes(OWNER)); 076 077 /** 078 * Used by rest interface to access this metadata attribute 079 * which denotes if the table is Read Only. 080 */ 081 @InterfaceAudience.Private 082 public static final String READONLY = "READONLY"; 083 private static final Bytes READONLY_KEY 084 = new Bytes(Bytes.toBytes(READONLY)); 085 086 /** 087 * Used by HBase Shell interface to access this metadata 088 * attribute which denotes if the table is compaction enabled. 089 */ 090 @InterfaceAudience.Private 091 public static final String COMPACTION_ENABLED = "COMPACTION_ENABLED"; 092 private static final Bytes COMPACTION_ENABLED_KEY 093 = new Bytes(Bytes.toBytes(COMPACTION_ENABLED)); 094 095 /** 096 * Used by HBase Shell interface to access this metadata 097 * attribute which denotes if the table is split enabled. 098 */ 099 @InterfaceAudience.Private 100 public static final String SPLIT_ENABLED = "SPLIT_ENABLED"; 101 private static final Bytes SPLIT_ENABLED_KEY = new Bytes(Bytes.toBytes(SPLIT_ENABLED)); 102 103 /** 104 * Used by HBase Shell interface to access this metadata 105 * attribute which denotes if the table is merge enabled. 106 */ 107 @InterfaceAudience.Private 108 public static final String MERGE_ENABLED = "MERGE_ENABLED"; 109 private static final Bytes MERGE_ENABLED_KEY = new Bytes(Bytes.toBytes(MERGE_ENABLED)); 110 111 /** 112 * Used by HBase Shell interface to access this metadata 113 * attribute which represents the maximum size of the memstore after which its 114 * contents are flushed onto the disk. 115 */ 116 @InterfaceAudience.Private 117 public static final String MEMSTORE_FLUSHSIZE = "MEMSTORE_FLUSHSIZE"; 118 private static final Bytes MEMSTORE_FLUSHSIZE_KEY 119 = new Bytes(Bytes.toBytes(MEMSTORE_FLUSHSIZE)); 120 121 @InterfaceAudience.Private 122 public static final String FLUSH_POLICY = "FLUSH_POLICY"; 123 private static final Bytes FLUSH_POLICY_KEY = new Bytes(Bytes.toBytes(FLUSH_POLICY)); 124 /** 125 * Used by rest interface to access this metadata attribute 126 * which denotes if it is a catalog table, either <code> hbase:meta </code>. 127 */ 128 @InterfaceAudience.Private 129 public static final String IS_META = "IS_META"; 130 private static final Bytes IS_META_KEY 131 = new Bytes(Bytes.toBytes(IS_META)); 132 133 /** 134 * {@link Durability} setting for the table. 135 */ 136 @InterfaceAudience.Private 137 public static final String DURABILITY = "DURABILITY"; 138 private static final Bytes DURABILITY_KEY 139 = new Bytes(Bytes.toBytes("DURABILITY")); 140 141 /** 142 * The number of region replicas for the table. 143 */ 144 @InterfaceAudience.Private 145 public static final String REGION_REPLICATION = "REGION_REPLICATION"; 146 private static final Bytes REGION_REPLICATION_KEY 147 = new Bytes(Bytes.toBytes(REGION_REPLICATION)); 148 149 /** 150 * The flag to indicate whether or not the memstore should be 151 * replicated for read-replicas (CONSISTENCY => TIMELINE). 152 */ 153 @InterfaceAudience.Private 154 public static final String REGION_MEMSTORE_REPLICATION = "REGION_MEMSTORE_REPLICATION"; 155 private static final Bytes REGION_MEMSTORE_REPLICATION_KEY 156 = new Bytes(Bytes.toBytes(REGION_MEMSTORE_REPLICATION)); 157 158 private static final Bytes REGION_REPLICA_WAIT_FOR_PRIMARY_FLUSH_CONF_KEY 159 = new Bytes(Bytes.toBytes(RegionReplicaUtil.REGION_REPLICA_WAIT_FOR_PRIMARY_FLUSH_CONF_KEY)); 160 /** 161 * Used by shell/rest interface to access this metadata 162 * attribute which denotes if the table should be treated by region 163 * normalizer. 164 */ 165 @InterfaceAudience.Private 166 public static final String NORMALIZATION_ENABLED = "NORMALIZATION_ENABLED"; 167 private static final Bytes NORMALIZATION_ENABLED_KEY 168 = new Bytes(Bytes.toBytes(NORMALIZATION_ENABLED)); 169 170 @InterfaceAudience.Private 171 public static final String NORMALIZER_TARGET_REGION_COUNT = 172 "NORMALIZER_TARGET_REGION_COUNT"; 173 private static final Bytes NORMALIZER_TARGET_REGION_COUNT_KEY = 174 new Bytes(Bytes.toBytes(NORMALIZER_TARGET_REGION_COUNT)); 175 176 @InterfaceAudience.Private 177 public static final String NORMALIZER_TARGET_REGION_SIZE = "NORMALIZER_TARGET_REGION_SIZE"; 178 private static final Bytes NORMALIZER_TARGET_REGION_SIZE_KEY = 179 new Bytes(Bytes.toBytes(NORMALIZER_TARGET_REGION_SIZE)); 180 181 /** 182 * Default durability for HTD is USE_DEFAULT, which defaults to HBase-global 183 * default value 184 */ 185 private static final Durability DEFAULT_DURABLITY = Durability.USE_DEFAULT; 186 187 @InterfaceAudience.Private 188 public static final String PRIORITY = "PRIORITY"; 189 private static final Bytes PRIORITY_KEY 190 = new Bytes(Bytes.toBytes(PRIORITY)); 191 192 /** 193 * Relative priority of the table used for rpc scheduling 194 */ 195 private static final int DEFAULT_PRIORITY = HConstants.NORMAL_QOS; 196 197 /** 198 * Constant that denotes whether the table is READONLY by default and is false 199 */ 200 public static final boolean DEFAULT_READONLY = false; 201 202 /** 203 * Constant that denotes whether the table is compaction enabled by default 204 */ 205 public static final boolean DEFAULT_COMPACTION_ENABLED = true; 206 207 /** 208 * Constant that denotes whether the table is split enabled by default 209 */ 210 public static final boolean DEFAULT_SPLIT_ENABLED = true; 211 212 /** 213 * Constant that denotes whether the table is merge enabled by default 214 */ 215 public static final boolean DEFAULT_MERGE_ENABLED = true; 216 217 /** 218 * Constant that denotes whether the table is normalized by default. 219 */ 220 public static final boolean DEFAULT_NORMALIZATION_ENABLED = false; 221 222 /** 223 * Constant that denotes the maximum default size of the memstore in bytes after which 224 * the contents are flushed to the store files. 225 */ 226 public static final long DEFAULT_MEMSTORE_FLUSH_SIZE = 1024 * 1024 * 128L; 227 228 public static final int DEFAULT_REGION_REPLICATION = 1; 229 230 public static final boolean DEFAULT_REGION_MEMSTORE_REPLICATION = true; 231 232 private final static Map<String, String> DEFAULT_VALUES = new HashMap<>(); 233 private final static Set<Bytes> RESERVED_KEYWORDS = new HashSet<>(); 234 235 static { 236 DEFAULT_VALUES.put(MAX_FILESIZE, 237 String.valueOf(HConstants.DEFAULT_MAX_FILE_SIZE)); 238 DEFAULT_VALUES.put(READONLY, String.valueOf(DEFAULT_READONLY)); 239 DEFAULT_VALUES.put(MEMSTORE_FLUSHSIZE, 240 String.valueOf(DEFAULT_MEMSTORE_FLUSH_SIZE)); 241 DEFAULT_VALUES.put(DURABILITY, DEFAULT_DURABLITY.name()); //use the enum name 242 DEFAULT_VALUES.put(REGION_REPLICATION, String.valueOf(DEFAULT_REGION_REPLICATION)); 243 DEFAULT_VALUES.put(NORMALIZATION_ENABLED, String.valueOf(DEFAULT_NORMALIZATION_ENABLED)); 244 DEFAULT_VALUES.put(PRIORITY, String.valueOf(DEFAULT_PRIORITY)); 245 DEFAULT_VALUES.keySet().stream() 246 .map(s -> new Bytes(Bytes.toBytes(s))).forEach(RESERVED_KEYWORDS::add); 247 RESERVED_KEYWORDS.add(IS_META_KEY); 248 } 249 250 @InterfaceAudience.Private 251 public final static String NAMESPACE_FAMILY_INFO = "info"; 252 @InterfaceAudience.Private 253 public final static byte[] NAMESPACE_FAMILY_INFO_BYTES = Bytes.toBytes(NAMESPACE_FAMILY_INFO); 254 @InterfaceAudience.Private 255 public final static byte[] NAMESPACE_COL_DESC_BYTES = Bytes.toBytes("d"); 256 257 /** 258 * <pre> 259 * Pattern that matches a coprocessor specification. Form is: 260 * {@code <coprocessor jar file location> '|' <class name> ['|' <priority> ['|' <arguments>]]} 261 * where arguments are {@code <KEY> '=' <VALUE> [,...]} 262 * For example: {@code hdfs:///foo.jar|com.foo.FooRegionObserver|1001|arg1=1,arg2=2} 263 * </pre> 264 */ 265 private static final Pattern CP_HTD_ATTR_VALUE_PATTERN = 266 Pattern.compile("(^[^\\|]*)\\|([^\\|]+)\\|[\\s]*([\\d]*)[\\s]*(\\|.*)?$"); 267 268 private static final String CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN = "[^=,]+"; 269 private static final String CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN = "[^,]+"; 270 private static final Pattern CP_HTD_ATTR_VALUE_PARAM_PATTERN = Pattern.compile( 271 "(" + CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN + ")=(" + 272 CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN + "),?"); 273 private static final Pattern CP_HTD_ATTR_KEY_PATTERN = 274 Pattern.compile("^coprocessor\\$([0-9]+)$", Pattern.CASE_INSENSITIVE); 275 /** 276 * Table descriptor for namespace table 277 */ 278 // TODO We used to set CacheDataInL1 for NS table. When we have BucketCache in file mode, now the 279 // NS data goes to File mode BC only. Test how that affect the system. If too much, we have to 280 // rethink about adding back the setCacheDataInL1 for NS table. 281 public static final TableDescriptor NAMESPACE_TABLEDESC 282 = TableDescriptorBuilder.newBuilder(TableName.NAMESPACE_TABLE_NAME) 283 .setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(NAMESPACE_FAMILY_INFO_BYTES) 284 // Ten is arbitrary number. Keep versions to help debugging. 285 .setMaxVersions(10) 286 .setInMemory(true) 287 .setBlocksize(8 * 1024) 288 .setScope(HConstants.REPLICATION_SCOPE_LOCAL) 289 .build()) 290 .build(); 291 private final ModifyableTableDescriptor desc; 292 293 /** 294 * @param desc The table descriptor to serialize 295 * @return This instance serialized with pb with pb magic prefix 296 */ 297 public static byte[] toByteArray(TableDescriptor desc) { 298 if (desc instanceof ModifyableTableDescriptor) { 299 return ((ModifyableTableDescriptor) desc).toByteArray(); 300 } 301 return new ModifyableTableDescriptor(desc).toByteArray(); 302 } 303 304 /** 305 * The input should be created by {@link #toByteArray}. 306 * @param pbBytes A pb serialized TableDescriptor instance with pb magic prefix 307 * @return This instance serialized with pb with pb magic prefix 308 * @throws org.apache.hadoop.hbase.exceptions.DeserializationException 309 */ 310 public static TableDescriptor parseFrom(byte[] pbBytes) throws DeserializationException { 311 return ModifyableTableDescriptor.parseFrom(pbBytes); 312 } 313 314 public static TableDescriptorBuilder newBuilder(final TableName name) { 315 return new TableDescriptorBuilder(name); 316 } 317 318 public static TableDescriptor copy(TableDescriptor desc) { 319 return new ModifyableTableDescriptor(desc); 320 } 321 322 public static TableDescriptor copy(TableName name, TableDescriptor desc) { 323 return new ModifyableTableDescriptor(name, desc); 324 } 325 326 /** 327 * Copy all values, families, and name from the input. 328 * @param desc The desciptor to copy 329 * @return A clone of input 330 */ 331 public static TableDescriptorBuilder newBuilder(final TableDescriptor desc) { 332 return new TableDescriptorBuilder(desc); 333 } 334 335 private TableDescriptorBuilder(final TableName name) { 336 this.desc = new ModifyableTableDescriptor(name); 337 } 338 339 private TableDescriptorBuilder(final TableDescriptor desc) { 340 this.desc = new ModifyableTableDescriptor(desc); 341 } 342 343 /** 344 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. 345 * Use {@link #setCoprocessor(String)} instead 346 */ 347 @Deprecated 348 public TableDescriptorBuilder addCoprocessor(String className) throws IOException { 349 return addCoprocessor(className, null, Coprocessor.PRIORITY_USER, null); 350 } 351 352 /** 353 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. 354 * Use {@link #setCoprocessor(CoprocessorDescriptor)} instead 355 */ 356 @Deprecated 357 public TableDescriptorBuilder addCoprocessor(String className, Path jarFilePath, 358 int priority, final Map<String, String> kvs) throws IOException { 359 desc.setCoprocessor( 360 CoprocessorDescriptorBuilder.newBuilder(className) 361 .setJarPath(jarFilePath == null ? null : jarFilePath.toString()) 362 .setPriority(priority) 363 .setProperties(kvs == null ? Collections.emptyMap() : kvs) 364 .build()); 365 return this; 366 } 367 368 /** 369 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. 370 * Use {@link #setCoprocessor(CoprocessorDescriptor)} instead 371 */ 372 @Deprecated 373 public TableDescriptorBuilder addCoprocessorWithSpec(final String specStr) throws IOException { 374 desc.setCoprocessorWithSpec(specStr); 375 return this; 376 } 377 378 /** 379 * @deprecated As of release 2.0.0, this will be removed in HBase 3.0.0. 380 * Use {@link #setColumnFamily(ColumnFamilyDescriptor)} instead 381 */ 382 @Deprecated 383 public TableDescriptorBuilder addColumnFamily(final ColumnFamilyDescriptor family) { 384 desc.setColumnFamily(family); 385 return this; 386 } 387 388 public TableDescriptorBuilder setCoprocessor(String className) throws IOException { 389 return setCoprocessor(CoprocessorDescriptorBuilder.of(className)); 390 } 391 392 public TableDescriptorBuilder setCoprocessor(CoprocessorDescriptor cpDesc) throws IOException { 393 desc.setCoprocessor(Objects.requireNonNull(cpDesc)); 394 return this; 395 } 396 397 public TableDescriptorBuilder setCoprocessors(Collection<CoprocessorDescriptor> cpDescs) 398 throws IOException { 399 for (CoprocessorDescriptor cpDesc : cpDescs) { 400 desc.setCoprocessor(cpDesc); 401 } 402 return this; 403 } 404 405 public TableDescriptorBuilder setColumnFamily(final ColumnFamilyDescriptor family) { 406 desc.setColumnFamily(Objects.requireNonNull(family)); 407 return this; 408 } 409 410 public TableDescriptorBuilder setColumnFamilies( 411 final Collection<ColumnFamilyDescriptor> families) { 412 families.forEach(desc::setColumnFamily); 413 return this; 414 } 415 416 public TableDescriptorBuilder modifyColumnFamily(final ColumnFamilyDescriptor family) { 417 desc.modifyColumnFamily(Objects.requireNonNull(family)); 418 return this; 419 } 420 421 public TableDescriptorBuilder removeValue(Bytes key) { 422 desc.removeValue(key); 423 return this; 424 } 425 426 public TableDescriptorBuilder removeValue(byte[] key) { 427 desc.removeValue(key); 428 return this; 429 } 430 431 public TableDescriptorBuilder removeColumnFamily(final byte[] name) { 432 desc.removeColumnFamily(name); 433 return this; 434 } 435 436 public TableDescriptorBuilder removeCoprocessor(String className) { 437 desc.removeCoprocessor(className); 438 return this; 439 } 440 441 public TableDescriptorBuilder setCompactionEnabled(final boolean isEnable) { 442 desc.setCompactionEnabled(isEnable); 443 return this; 444 } 445 446 public TableDescriptorBuilder setSplitEnabled(final boolean isEnable) { 447 desc.setSplitEnabled(isEnable); 448 return this; 449 } 450 451 public TableDescriptorBuilder setMergeEnabled(final boolean isEnable) { 452 desc.setMergeEnabled(isEnable); 453 return this; 454 } 455 456 public TableDescriptorBuilder setDurability(Durability durability) { 457 desc.setDurability(durability); 458 return this; 459 } 460 461 public TableDescriptorBuilder setFlushPolicyClassName(String clazz) { 462 desc.setFlushPolicyClassName(clazz); 463 return this; 464 } 465 466 public TableDescriptorBuilder setMaxFileSize(long maxFileSize) { 467 desc.setMaxFileSize(maxFileSize); 468 return this; 469 } 470 471 public TableDescriptorBuilder setMemStoreFlushSize(long memstoreFlushSize) { 472 desc.setMemStoreFlushSize(memstoreFlushSize); 473 return this; 474 } 475 476 public TableDescriptorBuilder setNormalizerTargetRegionCount(final int regionCount) { 477 desc.setNormalizerTargetRegionCount(regionCount); 478 return this; 479 } 480 481 public TableDescriptorBuilder setNormalizerTargetRegionSize(final long regionSize) { 482 desc.setNormalizerTargetRegionSize(regionSize); 483 return this; 484 } 485 486 public TableDescriptorBuilder setNormalizationEnabled(final boolean isEnable) { 487 desc.setNormalizationEnabled(isEnable); 488 return this; 489 } 490 491 @Deprecated 492 public TableDescriptorBuilder setOwner(User owner) { 493 desc.setOwner(owner); 494 return this; 495 } 496 497 @Deprecated 498 public TableDescriptorBuilder setOwnerString(String ownerString) { 499 desc.setOwnerString(ownerString); 500 return this; 501 } 502 503 public TableDescriptorBuilder setPriority(int priority) { 504 desc.setPriority(priority); 505 return this; 506 } 507 508 public TableDescriptorBuilder setReadOnly(final boolean readOnly) { 509 desc.setReadOnly(readOnly); 510 return this; 511 } 512 513 public TableDescriptorBuilder setRegionMemStoreReplication(boolean memstoreReplication) { 514 desc.setRegionMemStoreReplication(memstoreReplication); 515 return this; 516 } 517 518 public TableDescriptorBuilder setRegionReplication(int regionReplication) { 519 desc.setRegionReplication(regionReplication); 520 return this; 521 } 522 523 public TableDescriptorBuilder setRegionSplitPolicyClassName(String clazz) { 524 desc.setRegionSplitPolicyClassName(clazz); 525 return this; 526 } 527 528 public TableDescriptorBuilder setValue(final String key, final String value) { 529 desc.setValue(key, value); 530 return this; 531 } 532 533 public TableDescriptorBuilder setValue(final Bytes key, final Bytes value) { 534 desc.setValue(key, value); 535 return this; 536 } 537 538 public TableDescriptorBuilder setValue(final byte[] key, final byte[] value) { 539 desc.setValue(key, value); 540 return this; 541 } 542 543 /** 544 * Sets replication scope all & only the columns already in the builder. Columns added later won't 545 * be backfilled with replication scope. 546 * @param scope replication scope 547 * @return a TableDescriptorBuilder 548 */ 549 public TableDescriptorBuilder setReplicationScope(int scope) { 550 Map<byte[], ColumnFamilyDescriptor> newFamilies = new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR); 551 newFamilies.putAll(desc.families); 552 newFamilies 553 .forEach((cf, cfDesc) -> { 554 desc.removeColumnFamily(cf); 555 desc.setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(cfDesc).setScope(scope) 556 .build()); 557 }); 558 return this; 559 } 560 561 public TableDescriptor build() { 562 return new ModifyableTableDescriptor(desc); 563 } 564 565 /** 566 * TODO: make this private after removing the HTableDescriptor 567 */ 568 @InterfaceAudience.Private 569 public static class ModifyableTableDescriptor 570 implements TableDescriptor, Comparable<ModifyableTableDescriptor> { 571 572 private final TableName name; 573 574 /** 575 * A map which holds the metadata information of the table. This metadata 576 * includes values like IS_META, SPLIT_POLICY, MAX_FILE_SIZE, 577 * READONLY, MEMSTORE_FLUSHSIZE etc... 578 */ 579 private final Map<Bytes, Bytes> values = new HashMap<>(); 580 581 /** 582 * Maps column family name to the respective FamilyDescriptors 583 */ 584 private final Map<byte[], ColumnFamilyDescriptor> families 585 = new TreeMap<>(Bytes.BYTES_RAWCOMPARATOR); 586 587 /** 588 * Construct a table descriptor specifying a TableName object 589 * 590 * @param name Table name. 591 * TODO: make this private after removing the HTableDescriptor 592 */ 593 @InterfaceAudience.Private 594 public ModifyableTableDescriptor(final TableName name) { 595 this(name, Collections.EMPTY_LIST, Collections.EMPTY_MAP); 596 } 597 598 private ModifyableTableDescriptor(final TableDescriptor desc) { 599 this(desc.getTableName(), Arrays.asList(desc.getColumnFamilies()), desc.getValues()); 600 } 601 602 /** 603 * Construct a table descriptor by cloning the descriptor passed as a 604 * parameter. 605 * <p> 606 * Makes a deep copy of the supplied descriptor. 607 * @param name The new name 608 * @param desc The descriptor. 609 * TODO: make this private after removing the HTableDescriptor 610 */ 611 @InterfaceAudience.Private 612 @Deprecated // only used by HTableDescriptor. remove this method if HTD is removed 613 public ModifyableTableDescriptor(final TableName name, final TableDescriptor desc) { 614 this(name, Arrays.asList(desc.getColumnFamilies()), desc.getValues()); 615 } 616 617 private ModifyableTableDescriptor(final TableName name, final Collection<ColumnFamilyDescriptor> families, 618 Map<Bytes, Bytes> values) { 619 this.name = name; 620 families.forEach(c -> this.families.put(c.getName(), ColumnFamilyDescriptorBuilder.copy(c))); 621 this.values.putAll(values); 622 this.values.put(IS_META_KEY, 623 new Bytes(Bytes.toBytes(Boolean.toString(name.equals(TableName.META_TABLE_NAME))))); 624 } 625 626 /** 627 * Checks if this table is <code> hbase:meta </code> region. 628 * 629 * @return true if this table is <code> hbase:meta </code> region 630 */ 631 @Override 632 public boolean isMetaRegion() { 633 return getOrDefault(IS_META_KEY, Boolean::valueOf, false); 634 } 635 636 /** 637 * Checks if the table is a <code>hbase:meta</code> table 638 * 639 * @return true if table is <code> hbase:meta </code> region. 640 */ 641 @Override 642 public boolean isMetaTable() { 643 return isMetaRegion(); 644 } 645 646 @Override 647 public Bytes getValue(Bytes key) { 648 Bytes rval = values.get(key); 649 return rval == null ? null : new Bytes(rval.copyBytes()); 650 } 651 652 @Override 653 public String getValue(String key) { 654 Bytes rval = values.get(new Bytes(Bytes.toBytes(key))); 655 return rval == null ? null : Bytes.toString(rval.get(), rval.getOffset(), rval.getLength()); 656 } 657 658 @Override 659 public byte[] getValue(byte[] key) { 660 Bytes value = values.get(new Bytes(key)); 661 return value == null ? null : value.copyBytes(); 662 } 663 664 private <T> T getOrDefault(Bytes key, Function<String, T> function, T defaultValue) { 665 Bytes value = values.get(key); 666 if (value == null) { 667 return defaultValue; 668 } else { 669 return function.apply(Bytes.toString(value.get(), value.getOffset(), value.getLength())); 670 } 671 } 672 673 /** 674 * Getter for fetching an unmodifiable {@link #values} map. 675 * 676 * @return unmodifiable map {@link #values}. 677 * @see #values 678 */ 679 @Override 680 public Map<Bytes, Bytes> getValues() { 681 // shallow pointer copy 682 return Collections.unmodifiableMap(values); 683 } 684 685 /** 686 * Setter for storing metadata as a (key, value) pair in {@link #values} map 687 * 688 * @param key The key. 689 * @param value The value. If null, removes the setting. 690 * @return the modifyable TD 691 * @see #values 692 */ 693 public ModifyableTableDescriptor setValue(byte[] key, byte[] value) { 694 return setValue(toBytesOrNull(key, v -> v), 695 toBytesOrNull(value, v -> v)); 696 } 697 698 public ModifyableTableDescriptor setValue(String key, String value) { 699 return setValue(toBytesOrNull(key, Bytes::toBytes), 700 toBytesOrNull(value, Bytes::toBytes)); 701 } 702 703 /* 704 * @param key The key. 705 * @param value The value. If null, removes the setting. 706 */ 707 private ModifyableTableDescriptor setValue(final Bytes key, 708 final String value) { 709 return setValue(key, toBytesOrNull(value, Bytes::toBytes)); 710 } 711 712 /* 713 * Setter for storing metadata as a (key, value) pair in {@link #values} map 714 * 715 * @param key The key. 716 * @param value The value. If null, removes the setting. 717 */ 718 public ModifyableTableDescriptor setValue(final Bytes key, final Bytes value) { 719 if (value == null) { 720 values.remove(key); 721 } else { 722 values.put(key, value); 723 } 724 return this; 725 } 726 727 private static <T> Bytes toBytesOrNull(T t, Function<T, byte[]> f) { 728 if (t == null) { 729 return null; 730 } else { 731 return new Bytes(f.apply(t)); 732 } 733 } 734 735 /** 736 * Remove metadata represented by the key from the {@link #values} map 737 * 738 * @param key Key whose key and value we're to remove from TableDescriptor 739 * parameters. 740 * @return the modifyable TD 741 */ 742 public ModifyableTableDescriptor removeValue(Bytes key) { 743 return setValue(key, (Bytes) null); 744 } 745 746 /** 747 * Remove metadata represented by the key from the {@link #values} map 748 * 749 * @param key Key whose key and value we're to remove from TableDescriptor 750 * parameters. 751 * @return the modifyable TD 752 */ 753 public ModifyableTableDescriptor removeValue(final byte[] key) { 754 return removeValue(new Bytes(key)); 755 } 756 757 /** 758 * Check if the readOnly flag of the table is set. If the readOnly flag is 759 * set then the contents of the table can only be read from but not 760 * modified. 761 * 762 * @return true if all columns in the table should be read only 763 */ 764 @Override 765 public boolean isReadOnly() { 766 return getOrDefault(READONLY_KEY, Boolean::valueOf, DEFAULT_READONLY); 767 } 768 769 /** 770 * Setting the table as read only sets all the columns in the table as read 771 * only. By default all tables are modifiable, but if the readOnly flag is 772 * set to true then the contents of the table can only be read but not 773 * modified. 774 * 775 * @param readOnly True if all of the columns in the table should be read 776 * only. 777 * @return the modifyable TD 778 */ 779 public ModifyableTableDescriptor setReadOnly(final boolean readOnly) { 780 return setValue(READONLY_KEY, Boolean.toString(readOnly)); 781 } 782 783 /** 784 * Check if the compaction enable flag of the table is true. If flag is 785 * false then no minor/major compactions will be done in real. 786 * 787 * @return true if table compaction enabled 788 */ 789 @Override 790 public boolean isCompactionEnabled() { 791 return getOrDefault(COMPACTION_ENABLED_KEY, Boolean::valueOf, DEFAULT_COMPACTION_ENABLED); 792 } 793 794 /** 795 * Setting the table compaction enable flag. 796 * 797 * @param isEnable True if enable compaction. 798 * @return the modifyable TD 799 */ 800 public ModifyableTableDescriptor setCompactionEnabled(final boolean isEnable) { 801 return setValue(COMPACTION_ENABLED_KEY, Boolean.toString(isEnable)); 802 } 803 804 /** 805 * Check if the split enable flag of the table is true. If flag is false then no split will be 806 * done. 807 * 808 * @return true if table region split enabled 809 */ 810 @Override 811 public boolean isSplitEnabled() { 812 return getOrDefault(SPLIT_ENABLED_KEY, Boolean::valueOf, DEFAULT_SPLIT_ENABLED); 813 } 814 815 /** 816 * Setting the table region split enable flag. 817 * @param isEnable True if enable region split. 818 * 819 * @return the modifyable TD 820 */ 821 public ModifyableTableDescriptor setSplitEnabled(final boolean isEnable) { 822 return setValue(SPLIT_ENABLED_KEY, Boolean.toString(isEnable)); 823 } 824 825 /** 826 * Check if the region merge enable flag of the table is true. If flag is false then no merge 827 * will be done. 828 * 829 * @return true if table region merge enabled 830 */ 831 @Override 832 public boolean isMergeEnabled() { 833 return getOrDefault(MERGE_ENABLED_KEY, Boolean::valueOf, DEFAULT_MERGE_ENABLED); 834 } 835 836 /** 837 * Setting the table region merge enable flag. 838 * @param isEnable True if enable region merge. 839 * 840 * @return the modifyable TD 841 */ 842 public ModifyableTableDescriptor setMergeEnabled(final boolean isEnable) { 843 return setValue(MERGE_ENABLED_KEY, Boolean.toString(isEnable)); 844 } 845 846 /** 847 * Check if normalization enable flag of the table is true. If flag is false 848 * then no region normalizer won't attempt to normalize this table. 849 * 850 * @return true if region normalization is enabled for this table 851 */ 852 @Override 853 public boolean isNormalizationEnabled() { 854 return getOrDefault(NORMALIZATION_ENABLED_KEY, Boolean::valueOf, DEFAULT_NORMALIZATION_ENABLED); 855 } 856 857 /** 858 * Check if there is the target region count. If so, the normalize plan will be calculated based 859 * on the target region count. 860 * @return target region count after normalize done 861 */ 862 @Override 863 public int getNormalizerTargetRegionCount() { 864 return getOrDefault(NORMALIZER_TARGET_REGION_COUNT_KEY, Integer::valueOf, 865 Integer.valueOf(-1)); 866 } 867 868 /** 869 * Check if there is the target region size. If so, the normalize plan will be calculated based 870 * on the target region size. 871 * @return target region size after normalize done 872 */ 873 @Override 874 public long getNormalizerTargetRegionSize() { 875 return getOrDefault(NORMALIZER_TARGET_REGION_SIZE_KEY, Long::valueOf, Long.valueOf(-1)); 876 } 877 878 /** 879 * Setting the table normalization enable flag. 880 * 881 * @param isEnable True if enable normalization. 882 * @return the modifyable TD 883 */ 884 public ModifyableTableDescriptor setNormalizationEnabled(final boolean isEnable) { 885 return setValue(NORMALIZATION_ENABLED_KEY, Boolean.toString(isEnable)); 886 } 887 888 /** 889 * Setting the target region count of table normalization . 890 * @param regionCount the target region count. 891 * @return the modifyable TD 892 */ 893 public ModifyableTableDescriptor setNormalizerTargetRegionCount(final int regionCount) { 894 return setValue(NORMALIZER_TARGET_REGION_COUNT_KEY, Integer.toString(regionCount)); 895 } 896 897 /** 898 * Setting the target region size of table normalization. 899 * @param regionSize the target region size. 900 * @return the modifyable TD 901 */ 902 public ModifyableTableDescriptor setNormalizerTargetRegionSize(final long regionSize) { 903 return setValue(NORMALIZER_TARGET_REGION_SIZE_KEY, Long.toString(regionSize)); 904 } 905 906 /** 907 * Sets the {@link Durability} setting for the table. This defaults to 908 * Durability.USE_DEFAULT. 909 * 910 * @param durability enum value 911 * @return the modifyable TD 912 */ 913 public ModifyableTableDescriptor setDurability(Durability durability) { 914 return setValue(DURABILITY_KEY, durability.name()); 915 } 916 917 /** 918 * Returns the durability setting for the table. 919 * 920 * @return durability setting for the table. 921 */ 922 @Override 923 public Durability getDurability() { 924 return getOrDefault(DURABILITY_KEY, Durability::valueOf, DEFAULT_DURABLITY); 925 } 926 927 /** 928 * Get the name of the table 929 * 930 * @return TableName 931 */ 932 @Override 933 public TableName getTableName() { 934 return name; 935 } 936 937 /** 938 * This sets the class associated with the region split policy which 939 * determines when a region split should occur. The class used by default is 940 * defined in org.apache.hadoop.hbase.regionserver.RegionSplitPolicy 941 * 942 * @param clazz the class name 943 * @return the modifyable TD 944 */ 945 public ModifyableTableDescriptor setRegionSplitPolicyClassName(String clazz) { 946 return setValue(SPLIT_POLICY_KEY, clazz); 947 } 948 949 /** 950 * This gets the class associated with the region split policy which 951 * determines when a region split should occur. The class used by default is 952 * defined in org.apache.hadoop.hbase.regionserver.RegionSplitPolicy 953 * 954 * @return the class name of the region split policy for this table. If this 955 * returns null, the default split policy is used. 956 */ 957 @Override 958 public String getRegionSplitPolicyClassName() { 959 return getOrDefault(SPLIT_POLICY_KEY, Function.identity(), null); 960 } 961 962 /** 963 * Returns the maximum size upto which a region can grow to after which a 964 * region split is triggered. The region size is represented by the size of 965 * the biggest store file in that region. 966 * 967 * @return max hregion size for table, -1 if not set. 968 * 969 * @see #setMaxFileSize(long) 970 */ 971 @Override 972 public long getMaxFileSize() { 973 return getOrDefault(MAX_FILESIZE_KEY, Long::valueOf, (long) -1); 974 } 975 976 /** 977 * Sets the maximum size upto which a region can grow to after which a 978 * region split is triggered. The region size is represented by the size of 979 * the biggest store file in that region, i.e. If the biggest store file 980 * grows beyond the maxFileSize, then the region split is triggered. This 981 * defaults to a value of 256 MB. 982 * <p> 983 * This is not an absolute value and might vary. Assume that a single row 984 * exceeds the maxFileSize then the storeFileSize will be greater than 985 * maxFileSize since a single row cannot be split across multiple regions 986 * </p> 987 * 988 * @param maxFileSize The maximum file size that a store file can grow to 989 * before a split is triggered. 990 * @return the modifyable TD 991 */ 992 public ModifyableTableDescriptor setMaxFileSize(long maxFileSize) { 993 return setValue(MAX_FILESIZE_KEY, Long.toString(maxFileSize)); 994 } 995 996 /** 997 * Returns the size of the memstore after which a flush to filesystem is 998 * triggered. 999 * 1000 * @return memory cache flush size for each hregion, -1 if not set. 1001 * 1002 * @see #setMemStoreFlushSize(long) 1003 */ 1004 @Override 1005 public long getMemStoreFlushSize() { 1006 return getOrDefault(MEMSTORE_FLUSHSIZE_KEY, Long::valueOf, (long) -1); 1007 } 1008 1009 /** 1010 * Represents the maximum size of the memstore after which the contents of 1011 * the memstore are flushed to the filesystem. This defaults to a size of 64 1012 * MB. 1013 * 1014 * @param memstoreFlushSize memory cache flush size for each hregion 1015 * @return the modifyable TD 1016 */ 1017 public ModifyableTableDescriptor setMemStoreFlushSize(long memstoreFlushSize) { 1018 return setValue(MEMSTORE_FLUSHSIZE_KEY, Long.toString(memstoreFlushSize)); 1019 } 1020 1021 /** 1022 * This sets the class associated with the flush policy which determines 1023 * determines the stores need to be flushed when flushing a region. The 1024 * class used by default is defined in 1025 * org.apache.hadoop.hbase.regionserver.FlushPolicy. 1026 * 1027 * @param clazz the class name 1028 * @return the modifyable TD 1029 */ 1030 public ModifyableTableDescriptor setFlushPolicyClassName(String clazz) { 1031 return setValue(FLUSH_POLICY_KEY, clazz); 1032 } 1033 1034 /** 1035 * This gets the class associated with the flush policy which determines the 1036 * stores need to be flushed when flushing a region. The class used by 1037 * default is defined in org.apache.hadoop.hbase.regionserver.FlushPolicy. 1038 * 1039 * @return the class name of the flush policy for this table. If this 1040 * returns null, the default flush policy is used. 1041 */ 1042 @Override 1043 public String getFlushPolicyClassName() { 1044 return getOrDefault(FLUSH_POLICY_KEY, Function.identity(), null); 1045 } 1046 1047 /** 1048 * Adds a column family. For the updating purpose please use 1049 * {@link #modifyColumnFamily(ColumnFamilyDescriptor)} instead. 1050 * 1051 * @param family to add. 1052 * @return the modifyable TD 1053 */ 1054 public ModifyableTableDescriptor setColumnFamily(final ColumnFamilyDescriptor family) { 1055 if (family.getName() == null || family.getName().length <= 0) { 1056 throw new IllegalArgumentException("Family name cannot be null or empty"); 1057 } 1058 if (hasColumnFamily(family.getName())) { 1059 throw new IllegalArgumentException("Family '" 1060 + family.getNameAsString() + "' already exists so cannot be added"); 1061 } 1062 return putColumnFamily(family); 1063 } 1064 1065 /** 1066 * Modifies the existing column family. 1067 * 1068 * @param family to update 1069 * @return this (for chained invocation) 1070 */ 1071 public ModifyableTableDescriptor modifyColumnFamily(final ColumnFamilyDescriptor family) { 1072 if (family.getName() == null || family.getName().length <= 0) { 1073 throw new IllegalArgumentException("Family name cannot be null or empty"); 1074 } 1075 if (!hasColumnFamily(family.getName())) { 1076 throw new IllegalArgumentException("Column family '" + family.getNameAsString() 1077 + "' does not exist"); 1078 } 1079 return putColumnFamily(family); 1080 } 1081 1082 private ModifyableTableDescriptor putColumnFamily(ColumnFamilyDescriptor family) { 1083 families.put(family.getName(), family); 1084 return this; 1085 } 1086 1087 /** 1088 * Checks to see if this table contains the given column family 1089 * 1090 * @param familyName Family name or column name. 1091 * @return true if the table contains the specified family name 1092 */ 1093 @Override 1094 public boolean hasColumnFamily(final byte[] familyName) { 1095 return families.containsKey(familyName); 1096 } 1097 1098 /** 1099 * @return Name of this table and then a map of all of the column family descriptors. 1100 */ 1101 @Override 1102 public String toString() { 1103 StringBuilder s = new StringBuilder(); 1104 s.append('\'').append(Bytes.toString(name.getName())).append('\''); 1105 s.append(getValues(true)); 1106 families.values().forEach(f -> s.append(", ").append(f)); 1107 return s.toString(); 1108 } 1109 1110 /** 1111 * @return Name of this table and then a map of all of the column family 1112 * descriptors (with only the non-default column family attributes) 1113 */ 1114 @Override 1115 public String toStringCustomizedValues() { 1116 StringBuilder s = new StringBuilder(); 1117 s.append('\'').append(Bytes.toString(name.getName())).append('\''); 1118 s.append(getValues(false)); 1119 families.values().forEach(hcd -> s.append(", ").append(hcd.toStringCustomizedValues())); 1120 return s.toString(); 1121 } 1122 1123 /** 1124 * @return map of all table attributes formatted into string. 1125 */ 1126 public String toStringTableAttributes() { 1127 return getValues(true).toString(); 1128 } 1129 1130 private StringBuilder getValues(boolean printDefaults) { 1131 StringBuilder s = new StringBuilder(); 1132 1133 // step 1: set partitioning and pruning 1134 Set<Bytes> reservedKeys = new TreeSet<>(); 1135 Set<Bytes> userKeys = new TreeSet<>(); 1136 for (Map.Entry<Bytes, Bytes> entry : values.entrySet()) { 1137 if (entry.getKey() == null || entry.getKey().get() == null) { 1138 continue; 1139 } 1140 String key = Bytes.toString(entry.getKey().get()); 1141 // in this section, print out reserved keywords + coprocessor info 1142 if (!RESERVED_KEYWORDS.contains(entry.getKey()) && !key.startsWith("coprocessor$")) { 1143 userKeys.add(entry.getKey()); 1144 continue; 1145 } 1146 // only print out IS_META if true 1147 String value = Bytes.toString(entry.getValue().get()); 1148 if (key.equalsIgnoreCase(IS_META)) { 1149 if (Boolean.valueOf(value) == false) { 1150 continue; 1151 } 1152 } 1153 // see if a reserved key is a default value. may not want to print it out 1154 if (printDefaults 1155 || !DEFAULT_VALUES.containsKey(key) 1156 || !DEFAULT_VALUES.get(key).equalsIgnoreCase(value)) { 1157 reservedKeys.add(entry.getKey()); 1158 } 1159 } 1160 1161 // early exit optimization 1162 boolean hasAttributes = !reservedKeys.isEmpty() || !userKeys.isEmpty(); 1163 if (!hasAttributes) { 1164 return s; 1165 } 1166 1167 s.append(", {"); 1168 // step 2: printing attributes 1169 if (hasAttributes) { 1170 s.append("TABLE_ATTRIBUTES => {"); 1171 1172 // print all reserved keys first 1173 boolean printCommaForAttr = false; 1174 for (Bytes k : reservedKeys) { 1175 String key = Bytes.toString(k.get()); 1176 String value = Bytes.toStringBinary(values.get(k).get()); 1177 if (printCommaForAttr) { 1178 s.append(", "); 1179 } 1180 printCommaForAttr = true; 1181 s.append(key); 1182 s.append(" => "); 1183 s.append('\'').append(value).append('\''); 1184 } 1185 1186 if (!userKeys.isEmpty()) { 1187 // print all non-reserved as a separate subset 1188 if (printCommaForAttr) { 1189 s.append(", "); 1190 } 1191 s.append(HConstants.METADATA).append(" => "); 1192 s.append("{"); 1193 boolean printCommaForCfg = false; 1194 for (Bytes k : userKeys) { 1195 String key = Bytes.toString(k.get()); 1196 String value = Bytes.toStringBinary(values.get(k).get()); 1197 if (printCommaForCfg) { 1198 s.append(", "); 1199 } 1200 printCommaForCfg = true; 1201 s.append('\'').append(key).append('\''); 1202 s.append(" => "); 1203 s.append('\'').append(value).append('\''); 1204 } 1205 s.append("}"); 1206 } 1207 } 1208 1209 s.append("}"); // end METHOD 1210 return s; 1211 } 1212 1213 /** 1214 * Compare the contents of the descriptor with another one passed as a 1215 * parameter. Checks if the obj passed is an instance of ModifyableTableDescriptor, 1216 * if yes then the contents of the descriptors are compared. 1217 * 1218 * @param obj The object to compare 1219 * @return true if the contents of the the two descriptors exactly match 1220 * 1221 * @see java.lang.Object#equals(java.lang.Object) 1222 */ 1223 @Override 1224 public boolean equals(Object obj) { 1225 if (this == obj) { 1226 return true; 1227 } 1228 if (obj instanceof ModifyableTableDescriptor) { 1229 return TableDescriptor.COMPARATOR.compare(this, (ModifyableTableDescriptor) obj) == 0; 1230 } 1231 return false; 1232 } 1233 1234 /** 1235 * @return hash code 1236 */ 1237 @Override 1238 public int hashCode() { 1239 int result = this.name.hashCode(); 1240 if (this.families.size() > 0) { 1241 for (ColumnFamilyDescriptor e : this.families.values()) { 1242 result ^= e.hashCode(); 1243 } 1244 } 1245 result ^= values.hashCode(); 1246 return result; 1247 } 1248 1249 // Comparable 1250 /** 1251 * Compares the descriptor with another descriptor which is passed as a 1252 * parameter. This compares the content of the two descriptors and not the 1253 * reference. 1254 * 1255 * @param other The MTD to compare 1256 * @return 0 if the contents of the descriptors are exactly matching, 1 if 1257 * there is a mismatch in the contents 1258 */ 1259 @Override 1260 public int compareTo(final ModifyableTableDescriptor other) { 1261 return TableDescriptor.COMPARATOR.compare(this, other); 1262 } 1263 1264 @Override 1265 public ColumnFamilyDescriptor[] getColumnFamilies() { 1266 return families.values().toArray(new ColumnFamilyDescriptor[families.size()]); 1267 } 1268 1269 /** 1270 * Returns the configured replicas per region 1271 */ 1272 @Override 1273 public int getRegionReplication() { 1274 return getOrDefault(REGION_REPLICATION_KEY, Integer::valueOf, DEFAULT_REGION_REPLICATION); 1275 } 1276 1277 /** 1278 * Sets the number of replicas per region. 1279 * 1280 * @param regionReplication the replication factor per region 1281 * @return the modifyable TD 1282 */ 1283 public ModifyableTableDescriptor setRegionReplication(int regionReplication) { 1284 return setValue(REGION_REPLICATION_KEY, Integer.toString(regionReplication)); 1285 } 1286 1287 /** 1288 * @return true if the read-replicas memstore replication is enabled. 1289 */ 1290 @Override 1291 public boolean hasRegionMemStoreReplication() { 1292 return getOrDefault(REGION_MEMSTORE_REPLICATION_KEY, Boolean::valueOf, DEFAULT_REGION_MEMSTORE_REPLICATION); 1293 } 1294 1295 /** 1296 * Enable or Disable the memstore replication from the primary region to the 1297 * replicas. The replication will be used only for meta operations (e.g. 1298 * flush, compaction, ...) 1299 * 1300 * @param memstoreReplication true if the new data written to the primary 1301 * region should be replicated. false if the secondaries can tollerate to 1302 * have new data only when the primary flushes the memstore. 1303 * @return the modifyable TD 1304 */ 1305 public ModifyableTableDescriptor setRegionMemStoreReplication(boolean memstoreReplication) { 1306 setValue(REGION_MEMSTORE_REPLICATION_KEY, Boolean.toString(memstoreReplication)); 1307 // If the memstore replication is setup, we do not have to wait for observing a flush event 1308 // from primary before starting to serve reads, because gaps from replication is not applicable 1309 return setValue(REGION_REPLICA_WAIT_FOR_PRIMARY_FLUSH_CONF_KEY, 1310 Boolean.toString(memstoreReplication)); 1311 } 1312 1313 public ModifyableTableDescriptor setPriority(int priority) { 1314 return setValue(PRIORITY_KEY, Integer.toString(priority)); 1315 } 1316 1317 @Override 1318 public int getPriority() { 1319 return getOrDefault(PRIORITY_KEY, Integer::valueOf, DEFAULT_PRIORITY); 1320 } 1321 1322 /** 1323 * Returns all the column family names of the current table. The map of 1324 * TableDescriptor contains mapping of family name to ColumnFamilyDescriptor. 1325 * This returns all the keys of the family map which represents the column 1326 * family names of the table. 1327 * 1328 * @return Immutable sorted set of the keys of the families. 1329 */ 1330 @Override 1331 public Set<byte[]> getColumnFamilyNames() { 1332 return Collections.unmodifiableSet(this.families.keySet()); 1333 } 1334 1335 /** 1336 * Returns the ColumnFamilyDescriptor for a specific column family with name as 1337 * specified by the parameter column. 1338 * 1339 * @param column Column family name 1340 * @return Column descriptor for the passed family name or the family on 1341 * passed in column. 1342 */ 1343 @Override 1344 public ColumnFamilyDescriptor getColumnFamily(final byte[] column) { 1345 return this.families.get(column); 1346 } 1347 1348 /** 1349 * Removes the ColumnFamilyDescriptor with name specified by the parameter column 1350 * from the table descriptor 1351 * 1352 * @param column Name of the column family to be removed. 1353 * @return Column descriptor for the passed family name or the family on 1354 * passed in column. 1355 */ 1356 public ColumnFamilyDescriptor removeColumnFamily(final byte[] column) { 1357 return this.families.remove(column); 1358 } 1359 1360 /** 1361 * Add a table coprocessor to this table. The coprocessor type must be 1362 * org.apache.hadoop.hbase.coprocessor.RegionObserver or Endpoint. It won't 1363 * check if the class can be loaded or not. Whether a coprocessor is 1364 * loadable or not will be determined when a region is opened. 1365 * 1366 * @param className Full class name. 1367 * @throws IOException 1368 * @return the modifyable TD 1369 */ 1370 public ModifyableTableDescriptor setCoprocessor(String className) throws IOException { 1371 return setCoprocessor( 1372 CoprocessorDescriptorBuilder.newBuilder(className).setPriority(Coprocessor.PRIORITY_USER) 1373 .build()); 1374 } 1375 1376 /** 1377 * Add a table coprocessor to this table. The coprocessor type must be 1378 * org.apache.hadoop.hbase.coprocessor.RegionObserver or Endpoint. It won't 1379 * check if the class can be loaded or not. Whether a coprocessor is 1380 * loadable or not will be determined when a region is opened. 1381 * 1382 * @throws IOException any illegal parameter key/value 1383 * @return the modifyable TD 1384 */ 1385 public ModifyableTableDescriptor setCoprocessor(CoprocessorDescriptor cp) 1386 throws IOException { 1387 checkHasCoprocessor(cp.getClassName()); 1388 if (cp.getPriority() < 0) { 1389 throw new IOException("Priority must be bigger than or equal with zero, current:" 1390 + cp.getPriority()); 1391 } 1392 // Validate parameter kvs and then add key/values to kvString. 1393 StringBuilder kvString = new StringBuilder(); 1394 for (Map.Entry<String, String> e : cp.getProperties().entrySet()) { 1395 if (!e.getKey().matches(CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN)) { 1396 throw new IOException("Illegal parameter key = " + e.getKey()); 1397 } 1398 if (!e.getValue().matches(CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN)) { 1399 throw new IOException("Illegal parameter (" + e.getKey() 1400 + ") value = " + e.getValue()); 1401 } 1402 if (kvString.length() != 0) { 1403 kvString.append(','); 1404 } 1405 kvString.append(e.getKey()); 1406 kvString.append('='); 1407 kvString.append(e.getValue()); 1408 } 1409 1410 String value = cp.getJarPath().orElse("") 1411 + "|" + cp.getClassName() + "|" + Integer.toString(cp.getPriority()) + "|" 1412 + kvString.toString(); 1413 return setCoprocessorToMap(value); 1414 } 1415 1416 /** 1417 * Add a table coprocessor to this table. The coprocessor type must be 1418 * org.apache.hadoop.hbase.coprocessor.RegionObserver or Endpoint. It won't 1419 * check if the class can be loaded or not. Whether a coprocessor is 1420 * loadable or not will be determined when a region is opened. 1421 * 1422 * @param specStr The Coprocessor specification all in in one String 1423 * @throws IOException 1424 * @return the modifyable TD 1425 * @deprecated used by HTableDescriptor and admin.rb. 1426 * As of release 2.0.0, this will be removed in HBase 3.0.0. 1427 */ 1428 @Deprecated 1429 public ModifyableTableDescriptor setCoprocessorWithSpec(final String specStr) 1430 throws IOException { 1431 CoprocessorDescriptor cpDesc = toCoprocessorDescriptor(specStr).orElseThrow( 1432 () -> new IllegalArgumentException( 1433 "Format does not match " + CP_HTD_ATTR_VALUE_PATTERN + ": " + specStr)); 1434 checkHasCoprocessor(cpDesc.getClassName()); 1435 return setCoprocessorToMap(specStr); 1436 } 1437 1438 private void checkHasCoprocessor(final String className) throws IOException { 1439 if (hasCoprocessor(className)) { 1440 throw new IOException("Coprocessor " + className + " already exists."); 1441 } 1442 } 1443 1444 /** 1445 * Add coprocessor to values Map 1446 * @param specStr The Coprocessor specification all in in one String 1447 * @return Returns <code>this</code> 1448 */ 1449 private ModifyableTableDescriptor setCoprocessorToMap(final String specStr) { 1450 if (specStr == null) { 1451 return this; 1452 } 1453 // generate a coprocessor key 1454 int maxCoprocessorNumber = 0; 1455 Matcher keyMatcher; 1456 for (Map.Entry<Bytes, Bytes> e : this.values.entrySet()) { 1457 keyMatcher = CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e.getKey().get())); 1458 if (!keyMatcher.matches()) { 1459 continue; 1460 } 1461 maxCoprocessorNumber = Math.max(Integer.parseInt(keyMatcher.group(1)), maxCoprocessorNumber); 1462 } 1463 maxCoprocessorNumber++; 1464 String key = "coprocessor$" + Integer.toString(maxCoprocessorNumber); 1465 return setValue(new Bytes(Bytes.toBytes(key)), new Bytes(Bytes.toBytes(specStr))); 1466 } 1467 1468 /** 1469 * Check if the table has an attached co-processor represented by the name 1470 * className 1471 * 1472 * @param classNameToMatch - Class name of the co-processor 1473 * @return true of the table has a co-processor className 1474 */ 1475 @Override 1476 public boolean hasCoprocessor(String classNameToMatch) { 1477 return getCoprocessorDescriptors().stream().anyMatch(cp -> cp.getClassName() 1478 .equals(classNameToMatch)); 1479 } 1480 1481 /** 1482 * Return the list of attached co-processor represented by their name 1483 * className 1484 * 1485 * @return The list of co-processors classNames 1486 */ 1487 @Override 1488 public List<CoprocessorDescriptor> getCoprocessorDescriptors() { 1489 List<CoprocessorDescriptor> result = new ArrayList<>(); 1490 for (Map.Entry<Bytes, Bytes> e: getValues().entrySet()) { 1491 String key = Bytes.toString(e.getKey().get()).trim(); 1492 if (CP_HTD_ATTR_KEY_PATTERN.matcher(key).matches()) { 1493 toCoprocessorDescriptor(Bytes.toString(e.getValue().get()).trim()) 1494 .ifPresent(result::add); 1495 } 1496 } 1497 return result; 1498 } 1499 1500 /** 1501 * Remove a coprocessor from those set on the table 1502 * 1503 * @param className Class name of the co-processor 1504 */ 1505 public void removeCoprocessor(String className) { 1506 Bytes match = null; 1507 Matcher keyMatcher; 1508 Matcher valueMatcher; 1509 for (Map.Entry<Bytes, Bytes> e : this.values 1510 .entrySet()) { 1511 keyMatcher = CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e 1512 .getKey().get())); 1513 if (!keyMatcher.matches()) { 1514 continue; 1515 } 1516 valueMatcher = CP_HTD_ATTR_VALUE_PATTERN.matcher(Bytes 1517 .toString(e.getValue().get())); 1518 if (!valueMatcher.matches()) { 1519 continue; 1520 } 1521 // get className and compare 1522 String clazz = valueMatcher.group(2).trim(); // classname is the 2nd field 1523 // remove the CP if it is present 1524 if (clazz.equals(className.trim())) { 1525 match = e.getKey(); 1526 break; 1527 } 1528 } 1529 // if we found a match, remove it 1530 if (match != null) { 1531 ModifyableTableDescriptor.this.removeValue(match); 1532 } 1533 } 1534 1535 @Deprecated 1536 public ModifyableTableDescriptor setOwner(User owner) { 1537 return setOwnerString(owner != null ? owner.getShortName() : null); 1538 } 1539 1540 // used by admin.rb:alter(table_name,*args) to update owner. 1541 @Deprecated 1542 public ModifyableTableDescriptor setOwnerString(String ownerString) { 1543 return setValue(OWNER_KEY, ownerString); 1544 } 1545 1546 @Override 1547 @Deprecated 1548 public String getOwnerString() { 1549 // Note that every table should have an owner (i.e. should have OWNER_KEY set). 1550 // hbase:meta should return system user as owner, not null (see 1551 // MasterFileSystem.java:bootstrap()). 1552 return getOrDefault(OWNER_KEY, Function.identity(), null); 1553 } 1554 1555 /** 1556 * @return the bytes in pb format 1557 */ 1558 private byte[] toByteArray() { 1559 return ProtobufUtil.prependPBMagic(ProtobufUtil.toTableSchema(this).toByteArray()); 1560 } 1561 1562 /** 1563 * @param bytes A pb serialized {@link ModifyableTableDescriptor} instance 1564 * with pb magic prefix 1565 * @return An instance of {@link ModifyableTableDescriptor} made from 1566 * <code>bytes</code> 1567 * @throws DeserializationException 1568 * @see #toByteArray() 1569 */ 1570 private static TableDescriptor parseFrom(final byte[] bytes) 1571 throws DeserializationException { 1572 if (!ProtobufUtil.isPBMagicPrefix(bytes)) { 1573 throw new DeserializationException("Expected PB encoded ModifyableTableDescriptor"); 1574 } 1575 int pblen = ProtobufUtil.lengthOfPBMagic(); 1576 HBaseProtos.TableSchema.Builder builder = HBaseProtos.TableSchema.newBuilder(); 1577 try { 1578 ProtobufUtil.mergeFrom(builder, bytes, pblen, bytes.length - pblen); 1579 return ProtobufUtil.toTableDescriptor(builder.build()); 1580 } catch (IOException e) { 1581 throw new DeserializationException(e); 1582 } 1583 } 1584 1585 @Override 1586 public int getColumnFamilyCount() { 1587 return families.size(); 1588 } 1589 } 1590 1591 private static Optional<CoprocessorDescriptor> toCoprocessorDescriptor(String spec) { 1592 Matcher matcher = CP_HTD_ATTR_VALUE_PATTERN.matcher(spec); 1593 if (matcher.matches()) { 1594 // jar file path can be empty if the cp class can be loaded 1595 // from class loader. 1596 String path = matcher.group(1).trim().isEmpty() ? 1597 null : matcher.group(1).trim(); 1598 String className = matcher.group(2).trim(); 1599 if (className.isEmpty()) { 1600 return Optional.empty(); 1601 } 1602 String priorityStr = matcher.group(3).trim(); 1603 int priority = priorityStr.isEmpty() ? 1604 Coprocessor.PRIORITY_USER : Integer.parseInt(priorityStr); 1605 String cfgSpec = null; 1606 try { 1607 cfgSpec = matcher.group(4); 1608 } catch (IndexOutOfBoundsException ex) { 1609 // ignore 1610 } 1611 Map<String, String> ourConf = new TreeMap<>(); 1612 if (cfgSpec != null && !cfgSpec.trim().equals("|")) { 1613 cfgSpec = cfgSpec.substring(cfgSpec.indexOf('|') + 1); 1614 Matcher m = CP_HTD_ATTR_VALUE_PARAM_PATTERN.matcher(cfgSpec); 1615 while (m.find()) { 1616 ourConf.put(m.group(1), m.group(2)); 1617 } 1618 } 1619 return Optional.of(CoprocessorDescriptorBuilder.newBuilder(className) 1620 .setJarPath(path) 1621 .setPriority(priority) 1622 .setProperties(ourConf) 1623 .build()); 1624 } 1625 return Optional.empty(); 1626 } 1627}