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