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