View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase;
20  
21  import java.io.DataInput;
22  import java.io.DataOutput;
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.Collection;
26  import java.util.Collections;
27  import java.util.HashMap;
28  import java.util.HashSet;
29  import java.util.Iterator;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.TreeMap;
34  import java.util.TreeSet;
35  import java.util.regex.Matcher;
36  
37  import org.apache.hadoop.hbase.util.ByteStringer;
38  import org.apache.commons.logging.Log;
39  import org.apache.commons.logging.LogFactory;
40  import org.apache.hadoop.hbase.classification.InterfaceAudience;
41  import org.apache.hadoop.hbase.classification.InterfaceStability;
42  import org.apache.hadoop.conf.Configuration;
43  import org.apache.hadoop.fs.Path;
44  import org.apache.hadoop.hbase.client.Durability;
45  import org.apache.hadoop.hbase.client.RegionReplicaUtil;
46  import org.apache.hadoop.hbase.exceptions.DeserializationException;
47  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
48  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
49  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BytesBytesPair;
50  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ColumnFamilySchema;
51  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
52  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.TableSchema;
53  import org.apache.hadoop.hbase.regionserver.BloomType;
54  import org.apache.hadoop.hbase.security.User;
55  import org.apache.hadoop.hbase.util.Bytes;
56  import org.apache.hadoop.hbase.util.Writables;
57  import org.apache.hadoop.io.WritableComparable;
58  
59  import com.google.protobuf.InvalidProtocolBufferException;
60  
61  /**
62   * HTableDescriptor contains the details about an HBase table  such as the descriptors of
63   * all the column families, is the table a catalog table, <code> -ROOT- </code> or
64   * <code> hbase:meta </code>, if the table is read only, the maximum size of the memstore,
65   * when the region split should occur, coprocessors associated with it etc...
66   */
67  @InterfaceAudience.Public
68  @InterfaceStability.Evolving
69  public class HTableDescriptor implements WritableComparable<HTableDescriptor> {
70  
71    private static final Log LOG = LogFactory.getLog(HTableDescriptor.class);
72  
73    /**
74     *  Changes prior to version 3 were not recorded here.
75     *  Version 3 adds metadata as a map where keys and values are byte[].
76     *  Version 4 adds indexes
77     *  Version 5 removed transactional pollution -- e.g. indexes
78     *  Version 6 changed metadata to BytesBytesPair in PB
79     *  Version 7 adds table-level configuration
80     */
81    private static final byte TABLE_DESCRIPTOR_VERSION = 7;
82  
83    private TableName name = null;
84  
85    /**
86     * A map which holds the metadata information of the table. This metadata
87     * includes values like IS_ROOT, IS_META, DEFERRED_LOG_FLUSH, SPLIT_POLICY,
88     * MAX_FILE_SIZE, READONLY, MEMSTORE_FLUSHSIZE etc...
89     */
90    private final Map<ImmutableBytesWritable, ImmutableBytesWritable> values =
91      new HashMap<ImmutableBytesWritable, ImmutableBytesWritable>();
92  
93    /**
94     * A map which holds the configuration specific to the table.
95     * The keys of the map have the same names as config keys and override the defaults with
96     * table-specific settings. Example usage may be for compactions, etc.
97     */
98    private final Map<String, String> configuration = new HashMap<String, String>();
99  
100   public static final String SPLIT_POLICY = "SPLIT_POLICY";
101 
102   /**
103    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata
104    * attribute which denotes the maximum size of the store file after which
105    * a region split occurs
106    *
107    * @see #getMaxFileSize()
108    */
109   public static final String MAX_FILESIZE = "MAX_FILESIZE";
110   private static final ImmutableBytesWritable MAX_FILESIZE_KEY =
111     new ImmutableBytesWritable(Bytes.toBytes(MAX_FILESIZE));
112 
113   public static final String OWNER = "OWNER";
114   public static final ImmutableBytesWritable OWNER_KEY =
115     new ImmutableBytesWritable(Bytes.toBytes(OWNER));
116 
117   /**
118    * <em>INTERNAL</em> Used by rest interface to access this metadata
119    * attribute which denotes if the table is Read Only
120    *
121    * @see #isReadOnly()
122    */
123   public static final String READONLY = "READONLY";
124   private static final ImmutableBytesWritable READONLY_KEY =
125     new ImmutableBytesWritable(Bytes.toBytes(READONLY));
126 
127   /**
128    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata
129    * attribute which denotes if the table is compaction enabled
130    *
131    * @see #isCompactionEnabled()
132    */
133   public static final String COMPACTION_ENABLED = "COMPACTION_ENABLED";
134   private static final ImmutableBytesWritable COMPACTION_ENABLED_KEY =
135     new ImmutableBytesWritable(Bytes.toBytes(COMPACTION_ENABLED));
136 
137   /**
138    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata
139    * attribute which represents the maximum size of the memstore after which
140    * its contents are flushed onto the disk
141    *
142    * @see #getMemStoreFlushSize()
143    */
144   public static final String MEMSTORE_FLUSHSIZE = "MEMSTORE_FLUSHSIZE";
145   private static final ImmutableBytesWritable MEMSTORE_FLUSHSIZE_KEY =
146     new ImmutableBytesWritable(Bytes.toBytes(MEMSTORE_FLUSHSIZE));
147 
148   public static final String FLUSH_POLICY = "FLUSH_POLICY";
149 
150   /**
151    * <em>INTERNAL</em> Used by rest interface to access this metadata
152    * attribute which denotes if the table is a -ROOT- region or not
153    *
154    * @see #isRootRegion()
155    */
156   public static final String IS_ROOT = "IS_ROOT";
157   private static final ImmutableBytesWritable IS_ROOT_KEY =
158     new ImmutableBytesWritable(Bytes.toBytes(IS_ROOT));
159 
160   /**
161    * <em>INTERNAL</em> Used by rest interface to access this metadata
162    * attribute which denotes if it is a catalog table, either
163    * <code> hbase:meta </code> or <code> -ROOT- </code>
164    *
165    * @see #isMetaRegion()
166    */
167   public static final String IS_META = "IS_META";
168   private static final ImmutableBytesWritable IS_META_KEY =
169     new ImmutableBytesWritable(Bytes.toBytes(IS_META));
170 
171   /**
172    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata
173    * attribute which denotes if the deferred log flush option is enabled.
174    * @deprecated Use {@link #DURABILITY} instead.
175    */
176   @Deprecated
177   public static final String DEFERRED_LOG_FLUSH = "DEFERRED_LOG_FLUSH";
178   @Deprecated
179   private static final ImmutableBytesWritable DEFERRED_LOG_FLUSH_KEY =
180     new ImmutableBytesWritable(Bytes.toBytes(DEFERRED_LOG_FLUSH));
181 
182   /**
183    * <em>INTERNAL</em> {@link Durability} setting for the table.
184    */
185   public static final String DURABILITY = "DURABILITY";
186   private static final ImmutableBytesWritable DURABILITY_KEY =
187       new ImmutableBytesWritable(Bytes.toBytes("DURABILITY"));
188 
189   /**
190    * <em>INTERNAL</em> number of region replicas for the table.
191    */
192   public static final String REGION_REPLICATION = "REGION_REPLICATION";
193   private static final ImmutableBytesWritable REGION_REPLICATION_KEY =
194       new ImmutableBytesWritable(Bytes.toBytes(REGION_REPLICATION));
195 
196   /**
197    * <em>INTERNAL</em> flag to indicate whether or not the memstore should be replicated
198    * for read-replicas (CONSISTENCY => TIMELINE).
199    */
200   public static final String REGION_MEMSTORE_REPLICATION = "REGION_MEMSTORE_REPLICATION";
201   private static final ImmutableBytesWritable REGION_MEMSTORE_REPLICATION_KEY =
202       new ImmutableBytesWritable(Bytes.toBytes(REGION_MEMSTORE_REPLICATION));
203 
204   /** Default durability for HTD is USE_DEFAULT, which defaults to HBase-global default value */
205   private static final Durability DEFAULT_DURABLITY = Durability.USE_DEFAULT;
206 
207   /*
208    *  The below are ugly but better than creating them each time till we
209    *  replace booleans being saved as Strings with plain booleans.  Need a
210    *  migration script to do this.  TODO.
211    */
212   private static final ImmutableBytesWritable FALSE =
213     new ImmutableBytesWritable(Bytes.toBytes(Boolean.FALSE.toString()));
214 
215   private static final ImmutableBytesWritable TRUE =
216     new ImmutableBytesWritable(Bytes.toBytes(Boolean.TRUE.toString()));
217 
218   private static final boolean DEFAULT_DEFERRED_LOG_FLUSH = false;
219 
220   /**
221    * Constant that denotes whether the table is READONLY by default and is false
222    */
223   public static final boolean DEFAULT_READONLY = false;
224 
225   /**
226    * Constant that denotes whether the table is compaction enabled by default
227    */
228   public static final boolean DEFAULT_COMPACTION_ENABLED = true;
229 
230   /**
231    * Constant that denotes the maximum default size of the memstore after which
232    * the contents are flushed to the store files
233    */
234   public static final long DEFAULT_MEMSTORE_FLUSH_SIZE = 1024*1024*128L;
235 
236   public static final int DEFAULT_REGION_REPLICATION = 1;
237 
238   public static final boolean DEFAULT_REGION_MEMSTORE_REPLICATION = true;
239 
240   private final static Map<String, String> DEFAULT_VALUES
241     = new HashMap<String, String>();
242   private final static Set<ImmutableBytesWritable> RESERVED_KEYWORDS
243     = new HashSet<ImmutableBytesWritable>();
244   static {
245     DEFAULT_VALUES.put(MAX_FILESIZE,
246         String.valueOf(HConstants.DEFAULT_MAX_FILE_SIZE));
247     DEFAULT_VALUES.put(READONLY, String.valueOf(DEFAULT_READONLY));
248     DEFAULT_VALUES.put(MEMSTORE_FLUSHSIZE,
249         String.valueOf(DEFAULT_MEMSTORE_FLUSH_SIZE));
250     DEFAULT_VALUES.put(DEFERRED_LOG_FLUSH,
251         String.valueOf(DEFAULT_DEFERRED_LOG_FLUSH));
252     DEFAULT_VALUES.put(DURABILITY, DEFAULT_DURABLITY.name()); //use the enum name
253     DEFAULT_VALUES.put(REGION_REPLICATION, String.valueOf(DEFAULT_REGION_REPLICATION));
254     for (String s : DEFAULT_VALUES.keySet()) {
255       RESERVED_KEYWORDS.add(new ImmutableBytesWritable(Bytes.toBytes(s)));
256     }
257     RESERVED_KEYWORDS.add(IS_ROOT_KEY);
258     RESERVED_KEYWORDS.add(IS_META_KEY);
259   }
260 
261   /**
262    * Cache of whether this is a meta table or not.
263    */
264   private volatile Boolean meta = null;
265   /**
266    * Cache of whether this is root table or not.
267    */
268   private volatile Boolean root = null;
269 
270   /**
271    * Durability setting for the table
272    */
273   private Durability durability = null;
274 
275   /**
276    * Maps column family name to the respective HColumnDescriptors
277    */
278   private final Map<byte [], HColumnDescriptor> families =
279     new TreeMap<byte [], HColumnDescriptor>(Bytes.BYTES_RAWCOMPARATOR);
280 
281   /**
282    * <em> INTERNAL </em> Private constructor used internally creating table descriptors for
283    * catalog tables, <code>hbase:meta</code> and <code>-ROOT-</code>.
284    */
285   @InterfaceAudience.Private
286   protected HTableDescriptor(final TableName name, HColumnDescriptor[] families) {
287     setName(name);
288     for(HColumnDescriptor descriptor : families) {
289       this.families.put(descriptor.getName(), descriptor);
290     }
291   }
292 
293   /**
294    * <em> INTERNAL </em>Private constructor used internally creating table descriptors for
295    * catalog tables, <code>hbase:meta</code> and <code>-ROOT-</code>.
296    */
297   protected HTableDescriptor(final TableName name, HColumnDescriptor[] families,
298       Map<ImmutableBytesWritable,ImmutableBytesWritable> values) {
299     setName(name);
300     for(HColumnDescriptor descriptor : families) {
301       this.families.put(descriptor.getName(), descriptor);
302     }
303     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry:
304         values.entrySet()) {
305       setValue(entry.getKey(), entry.getValue());
306     }
307   }
308 
309   /**
310    * Default constructor which constructs an empty object.
311    * For deserializing an HTableDescriptor instance only.
312    * @deprecated As of release 0.96
313    *             (<a href="https://issues.apache.org/jira/browse/HBASE-5453">HBASE-5453</a>).
314    *             This will be removed in HBase 2.0.0.
315    *             Used by Writables and Writables are going away.
316    */
317   @Deprecated
318   public HTableDescriptor() {
319     super();
320   }
321 
322   /**
323    * Construct a table descriptor specifying a TableName object
324    * @param name Table name.
325    * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
326    */
327   public HTableDescriptor(final TableName name) {
328     super();
329     setName(name);
330   }
331 
332   /**
333    * Construct a table descriptor specifying a byte array table name
334    * @param name Table name.
335    * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
336    */
337   @Deprecated
338   public HTableDescriptor(final byte[] name) {
339     this(TableName.valueOf(name));
340   }
341 
342   /**
343    * Construct a table descriptor specifying a String table name
344    * @param name Table name.
345    * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
346    */
347   @Deprecated
348   public HTableDescriptor(final String name) {
349     this(TableName.valueOf(name));
350   }
351 
352   /**
353    * Construct a table descriptor by cloning the descriptor passed as a parameter.
354    * <p>
355    * Makes a deep copy of the supplied descriptor.
356    * Can make a modifiable descriptor from an UnmodifyableHTableDescriptor.
357    * @param desc The descriptor.
358    */
359   public HTableDescriptor(final HTableDescriptor desc) {
360     super();
361     setName(desc.name);
362     setMetaFlags(this.name);
363     for (HColumnDescriptor c: desc.families.values()) {
364       this.families.put(c.getName(), new HColumnDescriptor(c));
365     }
366     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
367         desc.values.entrySet()) {
368       setValue(e.getKey(), e.getValue());
369     }
370     for (Map.Entry<String, String> e : desc.configuration.entrySet()) {
371       this.configuration.put(e.getKey(), e.getValue());
372     }
373   }
374 
375   /*
376    * Set meta flags on this table.
377    * IS_ROOT_KEY is set if its a -ROOT- table
378    * IS_META_KEY is set either if its a -ROOT- or a hbase:meta table
379    * Called by constructors.
380    * @param name
381    */
382   private void setMetaFlags(final TableName name) {
383     setMetaRegion(isRootRegion() ||
384         name.equals(TableName.META_TABLE_NAME));
385   }
386 
387   /**
388    * Check if the descriptor represents a <code> -ROOT- </code> region.
389    *
390    * @return true if this is a <code> -ROOT- </code> region
391    */
392   public boolean isRootRegion() {
393     if (this.root == null) {
394       this.root = isSomething(IS_ROOT_KEY, false)? Boolean.TRUE: Boolean.FALSE;
395     }
396     return this.root.booleanValue();
397   }
398 
399   /**
400    * <em> INTERNAL </em> Used to denote if the current table represents
401    * <code> -ROOT- </code> region. This is used internally by the
402    * HTableDescriptor constructors
403    *
404    * @param isRoot true if this is the <code> -ROOT- </code> region
405    */
406   protected void setRootRegion(boolean isRoot) {
407     // TODO: Make the value a boolean rather than String of boolean.
408     setValue(IS_ROOT_KEY, isRoot? TRUE: FALSE);
409   }
410 
411   /**
412    * Checks if this table is <code> hbase:meta </code>
413    * region.
414    *
415    * @return true if this table is <code> hbase:meta </code>
416    * region
417    */
418   public boolean isMetaRegion() {
419     if (this.meta == null) {
420       this.meta = calculateIsMetaRegion();
421     }
422     return this.meta.booleanValue();
423   }
424 
425   private synchronized Boolean calculateIsMetaRegion() {
426     byte [] value = getValue(IS_META_KEY);
427     return (value != null)? Boolean.valueOf(Bytes.toString(value)): Boolean.FALSE;
428   }
429 
430   private boolean isSomething(final ImmutableBytesWritable key,
431       final boolean valueIfNull) {
432     byte [] value = getValue(key);
433     if (value != null) {
434       return Boolean.valueOf(Bytes.toString(value));
435     }
436     return valueIfNull;
437   }
438 
439   /**
440    * <em> INTERNAL </em> Used to denote if the current table represents
441    * <code> -ROOT- </code> or <code> hbase:meta </code> region. This is used
442    * internally by the HTableDescriptor constructors
443    *
444    * @param isMeta true if its either <code> -ROOT- </code> or
445    * <code> hbase:meta </code> region
446    */
447   protected void setMetaRegion(boolean isMeta) {
448     setValue(IS_META_KEY, isMeta? TRUE: FALSE);
449   }
450 
451   /**
452    * Checks if the table is a <code>hbase:meta</code> table
453    *
454    * @return true if table is <code> hbase:meta </code> region.
455    */
456   public boolean isMetaTable() {
457     return isMetaRegion() && !isRootRegion();
458   }
459 
460   /**
461    * Getter for accessing the metadata associated with the key
462    *
463    * @param key The key.
464    * @return The value.
465    * @see #values
466    */
467   public byte[] getValue(byte[] key) {
468     return getValue(new ImmutableBytesWritable(key));
469   }
470 
471   private byte[] getValue(final ImmutableBytesWritable key) {
472     ImmutableBytesWritable ibw = values.get(key);
473     if (ibw == null)
474       return null;
475     return ibw.get();
476   }
477 
478   /**
479    * Getter for accessing the metadata associated with the key
480    *
481    * @param key The key.
482    * @return The value.
483    * @see #values
484    */
485   public String getValue(String key) {
486     byte[] value = getValue(Bytes.toBytes(key));
487     if (value == null)
488       return null;
489     return Bytes.toString(value);
490   }
491 
492   /**
493    * Getter for fetching an unmodifiable {@link #values} map.
494    *
495    * @return unmodifiable map {@link #values}.
496    * @see #values
497    */
498   public Map<ImmutableBytesWritable,ImmutableBytesWritable> getValues() {
499     // shallow pointer copy
500     return Collections.unmodifiableMap(values);
501   }
502 
503   /**
504    * Setter for storing metadata as a (key, value) pair in {@link #values} map
505    *
506    * @param key The key.
507    * @param value The value.
508    * @see #values
509    */
510   public HTableDescriptor setValue(byte[] key, byte[] value) {
511     setValue(new ImmutableBytesWritable(key), new ImmutableBytesWritable(value));
512     return this;
513   }
514 
515   /*
516    * @param key The key.
517    * @param value The value.
518    */
519   private HTableDescriptor setValue(final ImmutableBytesWritable key,
520       final String value) {
521     setValue(key, new ImmutableBytesWritable(Bytes.toBytes(value)));
522     return this;
523   }
524 
525   /*
526    * Setter for storing metadata as a (key, value) pair in {@link #values} map
527    *
528    * @param key The key.
529    * @param value The value.
530    */
531   public HTableDescriptor setValue(final ImmutableBytesWritable key,
532       final ImmutableBytesWritable value) {
533     if (key.compareTo(DEFERRED_LOG_FLUSH_KEY) == 0) {
534       boolean isDeferredFlush = Boolean.valueOf(Bytes.toString(value.get()));
535       LOG.warn("HTableDescriptor property:" + DEFERRED_LOG_FLUSH + " is deprecated, " +
536           "use " + DURABILITY + " instead");
537       setDurability(isDeferredFlush ? Durability.ASYNC_WAL : DEFAULT_DURABLITY);
538       return this;
539     }
540     values.put(key, value);
541     return this;
542   }
543 
544   /**
545    * Setter for storing metadata as a (key, value) pair in {@link #values} map
546    *
547    * @param key The key.
548    * @param value The value.
549    * @see #values
550    */
551   public HTableDescriptor setValue(String key, String value) {
552     if (value == null) {
553       remove(key);
554     } else {
555       setValue(Bytes.toBytes(key), Bytes.toBytes(value));
556     }
557     return this;
558   }
559 
560   /**
561    * Remove metadata represented by the key from the {@link #values} map
562    *
563    * @param key Key whose key and value we're to remove from HTableDescriptor
564    * parameters.
565    */
566   public void remove(final String key) {
567     remove(new ImmutableBytesWritable(Bytes.toBytes(key)));
568   }
569 
570   /**
571    * Remove metadata represented by the key from the {@link #values} map
572    *
573    * @param key Key whose key and value we're to remove from HTableDescriptor
574    * parameters.
575    */
576   public void remove(ImmutableBytesWritable key) {
577     values.remove(key);
578   }
579 
580   /**
581    * Remove metadata represented by the key from the {@link #values} map
582    *
583    * @param key Key whose key and value we're to remove from HTableDescriptor
584    * parameters.
585    */
586   public void remove(final byte [] key) {
587     remove(new ImmutableBytesWritable(key));
588   }
589 
590   /**
591    * Check if the readOnly flag of the table is set. If the readOnly flag is
592    * set then the contents of the table can only be read from but not modified.
593    *
594    * @return true if all columns in the table should be read only
595    */
596   public boolean isReadOnly() {
597     return isSomething(READONLY_KEY, DEFAULT_READONLY);
598   }
599 
600   /**
601    * Setting the table as read only sets all the columns in the table as read
602    * only. By default all tables are modifiable, but if the readOnly flag is
603    * set to true then the contents of the table can only be read but not modified.
604    *
605    * @param readOnly True if all of the columns in the table should be read
606    * only.
607    */
608   public HTableDescriptor setReadOnly(final boolean readOnly) {
609     return setValue(READONLY_KEY, readOnly? TRUE: FALSE);
610   }
611 
612   /**
613    * Check if the compaction enable flag of the table is true. If flag is
614    * false then no minor/major compactions will be done in real.
615    *
616    * @return true if table compaction enabled
617    */
618   public boolean isCompactionEnabled() {
619     return isSomething(COMPACTION_ENABLED_KEY, DEFAULT_COMPACTION_ENABLED);
620   }
621 
622   /**
623    * Setting the table compaction enable flag.
624    *
625    * @param isEnable True if enable compaction.
626    */
627   public HTableDescriptor setCompactionEnabled(final boolean isEnable) {
628     setValue(COMPACTION_ENABLED_KEY, isEnable ? TRUE : FALSE);
629     return this;
630   }
631 
632   /**
633    * Sets the {@link Durability} setting for the table. This defaults to Durability.USE_DEFAULT.
634    * @param durability enum value
635    */
636   public HTableDescriptor setDurability(Durability durability) {
637     this.durability = durability;
638     setValue(DURABILITY_KEY, durability.name());
639     return this;
640   }
641 
642   /**
643    * Returns the durability setting for the table.
644    * @return durability setting for the table.
645    */
646   public Durability getDurability() {
647     if (this.durability == null) {
648       byte[] durabilityValue = getValue(DURABILITY_KEY);
649       if (durabilityValue == null) {
650         this.durability = DEFAULT_DURABLITY;
651       } else {
652         try {
653           this.durability = Durability.valueOf(Bytes.toString(durabilityValue));
654         } catch (IllegalArgumentException ex) {
655           LOG.warn("Received " + ex + " because Durability value for HTableDescriptor"
656             + " is not known. Durability:" + Bytes.toString(durabilityValue));
657           this.durability = DEFAULT_DURABLITY;
658         }
659       }
660     }
661     return this.durability;
662   }
663 
664   /**
665    * Get the name of the table
666    *
667    * @return TableName
668    */
669   public TableName getTableName() {
670     return name;
671   }
672 
673   /**
674    * Get the name of the table as a byte array.
675    *
676    * @return name of table
677    * @deprecated Use {@link #getTableName()} instead
678    */
679   @Deprecated
680   public byte[] getName() {
681     return name.getName();
682   }
683 
684   /**
685    * Get the name of the table as a String
686    *
687    * @return name of table as a String
688    */
689   public String getNameAsString() {
690     return name.getNameAsString();
691   }
692 
693   /**
694    * This sets the class associated with the region split policy which
695    * determines when a region split should occur.  The class used by
696    * default is defined in {@link org.apache.hadoop.hbase.regionserver.RegionSplitPolicy}
697    * @param clazz the class name
698    */
699   public HTableDescriptor setRegionSplitPolicyClassName(String clazz) {
700     setValue(SPLIT_POLICY, clazz);
701     return this;
702   }
703 
704   /**
705    * This gets the class associated with the region split policy which
706    * determines when a region split should occur.  The class used by
707    * default is defined in {@link org.apache.hadoop.hbase.regionserver.RegionSplitPolicy}
708    *
709    * @return the class name of the region split policy for this table.
710    * If this returns null, the default split policy is used.
711    */
712    public String getRegionSplitPolicyClassName() {
713     return getValue(SPLIT_POLICY);
714   }
715 
716   /**
717    * Set the name of the table.
718    *
719    * @param name name of table
720    */
721   @Deprecated
722   public HTableDescriptor setName(byte[] name) {
723     setName(TableName.valueOf(name));
724     return this;
725   }
726 
727   @Deprecated
728   public HTableDescriptor setName(TableName name) {
729     this.name = name;
730     setMetaFlags(this.name);
731     return this;
732   }
733 
734   /**
735    * Returns the maximum size upto which a region can grow to after which a region
736    * split is triggered. The region size is represented by the size of the biggest
737    * store file in that region.
738    *
739    * @return max hregion size for table, -1 if not set.
740    *
741    * @see #setMaxFileSize(long)
742    */
743   public long getMaxFileSize() {
744     byte [] value = getValue(MAX_FILESIZE_KEY);
745     if (value != null) {
746       return Long.parseLong(Bytes.toString(value));
747     }
748     return -1;
749   }
750 
751   /**
752    * Sets the maximum size upto which a region can grow to after which a region
753    * split is triggered. The region size is represented by the size of the biggest
754    * store file in that region, i.e. If the biggest store file grows beyond the
755    * maxFileSize, then the region split is triggered. This defaults to a value of
756    * 256 MB.
757    * <p>
758    * This is not an absolute value and might vary. Assume that a single row exceeds
759    * the maxFileSize then the storeFileSize will be greater than maxFileSize since
760    * a single row cannot be split across multiple regions
761    * </p>
762    *
763    * @param maxFileSize The maximum file size that a store file can grow to
764    * before a split is triggered.
765    */
766   public HTableDescriptor setMaxFileSize(long maxFileSize) {
767     setValue(MAX_FILESIZE_KEY, Long.toString(maxFileSize));
768     return this;
769   }
770 
771   /**
772    * Returns the size of the memstore after which a flush to filesystem is triggered.
773    *
774    * @return memory cache flush size for each hregion, -1 if not set.
775    *
776    * @see #setMemStoreFlushSize(long)
777    */
778   public long getMemStoreFlushSize() {
779     byte [] value = getValue(MEMSTORE_FLUSHSIZE_KEY);
780     if (value != null) {
781       return Long.parseLong(Bytes.toString(value));
782     }
783     return -1;
784   }
785 
786   /**
787    * Represents the maximum size of the memstore after which the contents of the
788    * memstore are flushed to the filesystem. This defaults to a size of 64 MB.
789    *
790    * @param memstoreFlushSize memory cache flush size for each hregion
791    */
792   public HTableDescriptor setMemStoreFlushSize(long memstoreFlushSize) {
793     setValue(MEMSTORE_FLUSHSIZE_KEY, Long.toString(memstoreFlushSize));
794     return this;
795   }
796 
797   /**
798    * This sets the class associated with the flush policy which determines determines the stores
799    * need to be flushed when flushing a region. The class used by default is defined in
800    * {@link org.apache.hadoop.hbase.regionserver.FlushPolicy}
801    * @param clazz the class name
802    */
803   public HTableDescriptor setFlushPolicyClassName(String clazz) {
804     setValue(FLUSH_POLICY, clazz);
805     return this;
806   }
807 
808   /**
809    * This gets the class associated with the flush policy which determines the stores need to be
810    * flushed when flushing a region. The class used by default is defined in
811    * {@link org.apache.hadoop.hbase.regionserver.FlushPolicy}
812    * @return the class name of the flush policy for this table. If this returns null, the default
813    *         flush policy is used.
814    */
815   public String getFlushPolicyClassName() {
816     return getValue(FLUSH_POLICY);
817   }
818 
819   /**
820    * Adds a column family.
821    * For the updating purpose please use {@link #modifyFamily(HColumnDescriptor)} instead.
822    * @param family HColumnDescriptor of family to add.
823    */
824   public HTableDescriptor addFamily(final HColumnDescriptor family) {
825     if (family.getName() == null || family.getName().length <= 0) {
826       throw new IllegalArgumentException("Family name cannot be null or empty");
827     }
828     if (hasFamily(family.getName())) {
829       throw new IllegalArgumentException("Family '" +
830         family.getNameAsString() + "' already exists so cannot be added");
831     }
832     this.families.put(family.getName(), family);
833     return this;
834   }
835 
836   /**
837    * Modifies the existing column family.
838    * @param family HColumnDescriptor of family to update
839    * @return this (for chained invocation)
840    */
841   public HTableDescriptor modifyFamily(final HColumnDescriptor family) {
842     if (family.getName() == null || family.getName().length <= 0) {
843       throw new IllegalArgumentException("Family name cannot be null or empty");
844     }
845     if (!hasFamily(family.getName())) {
846       throw new IllegalArgumentException("Column family '" + family.getNameAsString()
847         + "' does not exist");
848     }
849     this.families.put(family.getName(), family);
850     return this;
851   }
852 
853   /**
854    * Checks to see if this table contains the given column family
855    * @param familyName Family name or column name.
856    * @return true if the table contains the specified family name
857    */
858   public boolean hasFamily(final byte [] familyName) {
859     return families.containsKey(familyName);
860   }
861 
862   /**
863    * @return Name of this table and then a map of all of the column family
864    * descriptors.
865    * @see #getNameAsString()
866    */
867   @Override
868   public String toString() {
869     StringBuilder s = new StringBuilder();
870     s.append('\'').append(Bytes.toString(name.getName())).append('\'');
871     s.append(getValues(true));
872     for (HColumnDescriptor f : families.values()) {
873       s.append(", ").append(f);
874     }
875     return s.toString();
876   }
877 
878   /**
879    * @return Name of this table and then a map of all of the column family
880    * descriptors (with only the non-default column family attributes)
881    */
882   public String toStringCustomizedValues() {
883     StringBuilder s = new StringBuilder();
884     s.append('\'').append(Bytes.toString(name.getName())).append('\'');
885     s.append(getValues(false));
886     for(HColumnDescriptor hcd : families.values()) {
887       s.append(", ").append(hcd.toStringCustomizedValues());
888     }
889     return s.toString();
890   }
891 
892   /**
893    * @return map of all table attributes formatted into string.
894    */
895   public String toStringTableAttributes() {
896    return getValues(true).toString();
897   }
898 
899   private StringBuilder getValues(boolean printDefaults) {
900     StringBuilder s = new StringBuilder();
901 
902     // step 1: set partitioning and pruning
903     Set<ImmutableBytesWritable> reservedKeys = new TreeSet<ImmutableBytesWritable>();
904     Set<ImmutableBytesWritable> userKeys = new TreeSet<ImmutableBytesWritable>();
905     for (ImmutableBytesWritable k : values.keySet()) {
906       if (k == null || k.get() == null) continue;
907       String key = Bytes.toString(k.get());
908       // in this section, print out reserved keywords + coprocessor info
909       if (!RESERVED_KEYWORDS.contains(k) && !key.startsWith("coprocessor$")) {
910         userKeys.add(k);
911         continue;
912       }
913       // only print out IS_ROOT/IS_META if true
914       String value = Bytes.toString(values.get(k).get());
915       if (key.equalsIgnoreCase(IS_ROOT) || key.equalsIgnoreCase(IS_META)) {
916         if (Boolean.valueOf(value) == false) continue;
917       }
918       // see if a reserved key is a default value. may not want to print it out
919       if (printDefaults
920           || !DEFAULT_VALUES.containsKey(key)
921           || !DEFAULT_VALUES.get(key).equalsIgnoreCase(value)) {
922         reservedKeys.add(k);
923       }
924     }
925 
926     // early exit optimization
927     boolean hasAttributes = !reservedKeys.isEmpty() || !userKeys.isEmpty();
928     if (!hasAttributes && configuration.isEmpty()) return s;
929 
930     s.append(", {");
931     // step 2: printing attributes
932     if (hasAttributes) {
933       s.append("TABLE_ATTRIBUTES => {");
934 
935       // print all reserved keys first
936       boolean printCommaForAttr = false;
937       for (ImmutableBytesWritable k : reservedKeys) {
938         String key = Bytes.toString(k.get());
939         String value = Bytes.toStringBinary(values.get(k).get());
940         if (printCommaForAttr) s.append(", ");
941         printCommaForAttr = true;
942         s.append(key);
943         s.append(" => ");
944         s.append('\'').append(value).append('\'');
945       }
946 
947       if (!userKeys.isEmpty()) {
948         // print all non-reserved, advanced config keys as a separate subset
949         if (printCommaForAttr) s.append(", ");
950         printCommaForAttr = true;
951         s.append(HConstants.METADATA).append(" => ");
952         s.append("{");
953         boolean printCommaForCfg = false;
954         for (ImmutableBytesWritable k : userKeys) {
955           String key = Bytes.toString(k.get());
956           String value = Bytes.toStringBinary(values.get(k).get());
957           if (printCommaForCfg) s.append(", ");
958           printCommaForCfg = true;
959           s.append('\'').append(key).append('\'');
960           s.append(" => ");
961           s.append('\'').append(value).append('\'');
962         }
963         s.append("}");
964       }
965     }
966 
967     // step 3: printing all configuration:
968     if (!configuration.isEmpty()) {
969       if (hasAttributes) {
970         s.append(", ");
971       }
972       s.append(HConstants.CONFIGURATION).append(" => ");
973       s.append('{');
974       boolean printCommaForConfig = false;
975       for (Map.Entry<String, String> e : configuration.entrySet()) {
976         if (printCommaForConfig) s.append(", ");
977         printCommaForConfig = true;
978         s.append('\'').append(e.getKey()).append('\'');
979         s.append(" => ");
980         s.append('\'').append(e.getValue()).append('\'');
981       }
982       s.append("}");
983     }
984     s.append("}"); // end METHOD
985     return s;
986   }
987 
988   /**
989    * Compare the contents of the descriptor with another one passed as a parameter.
990    * Checks if the obj passed is an instance of HTableDescriptor, if yes then the
991    * contents of the descriptors are compared.
992    *
993    * @return true if the contents of the the two descriptors exactly match
994    *
995    * @see java.lang.Object#equals(java.lang.Object)
996    */
997   @Override
998   public boolean equals(Object obj) {
999     if (this == obj) {
1000       return true;
1001     }
1002     if (obj == null) {
1003       return false;
1004     }
1005     if (!(obj instanceof HTableDescriptor)) {
1006       return false;
1007     }
1008     return compareTo((HTableDescriptor)obj) == 0;
1009   }
1010 
1011   /**
1012    * @see java.lang.Object#hashCode()
1013    */
1014   @Override
1015   public int hashCode() {
1016     int result = this.name.hashCode();
1017     result ^= Byte.valueOf(TABLE_DESCRIPTOR_VERSION).hashCode();
1018     if (this.families != null && this.families.size() > 0) {
1019       for (HColumnDescriptor e: this.families.values()) {
1020         result ^= e.hashCode();
1021       }
1022     }
1023     result ^= values.hashCode();
1024     result ^= configuration.hashCode();
1025     return result;
1026   }
1027 
1028   /**
1029    * <em> INTERNAL </em> This method is a part of {@link WritableComparable} interface
1030    * and is used for de-serialization of the HTableDescriptor over RPC
1031    * @deprecated Writables are going away.  Use pb {@link #parseFrom(byte[])} instead.
1032    */
1033   @Deprecated
1034   @Override
1035   public void readFields(DataInput in) throws IOException {
1036     int version = in.readInt();
1037     if (version < 3)
1038       throw new IOException("versions < 3 are not supported (and never existed!?)");
1039     // version 3+
1040     name = TableName.valueOf(Bytes.readByteArray(in));
1041     setRootRegion(in.readBoolean());
1042     setMetaRegion(in.readBoolean());
1043     values.clear();
1044     configuration.clear();
1045     int numVals = in.readInt();
1046     for (int i = 0; i < numVals; i++) {
1047       ImmutableBytesWritable key = new ImmutableBytesWritable();
1048       ImmutableBytesWritable value = new ImmutableBytesWritable();
1049       key.readFields(in);
1050       value.readFields(in);
1051       setValue(key, value);
1052     }
1053     families.clear();
1054     int numFamilies = in.readInt();
1055     for (int i = 0; i < numFamilies; i++) {
1056       HColumnDescriptor c = new HColumnDescriptor();
1057       c.readFields(in);
1058       families.put(c.getName(), c);
1059     }
1060     if (version >= 7) {
1061       int numConfigs = in.readInt();
1062       for (int i = 0; i < numConfigs; i++) {
1063         ImmutableBytesWritable key = new ImmutableBytesWritable();
1064         ImmutableBytesWritable value = new ImmutableBytesWritable();
1065         key.readFields(in);
1066         value.readFields(in);
1067         configuration.put(
1068           Bytes.toString(key.get(), key.getOffset(), key.getLength()),
1069           Bytes.toString(value.get(), value.getOffset(), value.getLength()));
1070       }
1071     }
1072   }
1073 
1074   /**
1075    * <em> INTERNAL </em> This method is a part of {@link WritableComparable} interface
1076    * and is used for serialization of the HTableDescriptor over RPC
1077    * @deprecated Writables are going away.
1078    * Use {@link com.google.protobuf.MessageLite#toByteArray} instead.
1079    */
1080   @Deprecated
1081   @Override
1082   public void write(DataOutput out) throws IOException {
1083     out.writeInt(TABLE_DESCRIPTOR_VERSION);
1084     Bytes.writeByteArray(out, name.toBytes());
1085     out.writeBoolean(isRootRegion());
1086     out.writeBoolean(isMetaRegion());
1087     out.writeInt(values.size());
1088     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1089         values.entrySet()) {
1090       e.getKey().write(out);
1091       e.getValue().write(out);
1092     }
1093     out.writeInt(families.size());
1094     for(Iterator<HColumnDescriptor> it = families.values().iterator();
1095         it.hasNext(); ) {
1096       HColumnDescriptor family = it.next();
1097       family.write(out);
1098     }
1099     out.writeInt(configuration.size());
1100     for (Map.Entry<String, String> e : configuration.entrySet()) {
1101       new ImmutableBytesWritable(Bytes.toBytes(e.getKey())).write(out);
1102       new ImmutableBytesWritable(Bytes.toBytes(e.getValue())).write(out);
1103     }
1104   }
1105 
1106   // Comparable
1107 
1108   /**
1109    * Compares the descriptor with another descriptor which is passed as a parameter.
1110    * This compares the content of the two descriptors and not the reference.
1111    *
1112    * @return 0 if the contents of the descriptors are exactly matching,
1113    *         1 if there is a mismatch in the contents
1114    */
1115   @Override
1116   public int compareTo(final HTableDescriptor other) {
1117     int result = this.name.compareTo(other.name);
1118     if (result == 0) {
1119       result = families.size() - other.families.size();
1120     }
1121     if (result == 0 && families.size() != other.families.size()) {
1122       result = Integer.valueOf(families.size()).compareTo(
1123           Integer.valueOf(other.families.size()));
1124     }
1125     if (result == 0) {
1126       for (Iterator<HColumnDescriptor> it = families.values().iterator(),
1127           it2 = other.families.values().iterator(); it.hasNext(); ) {
1128         result = it.next().compareTo(it2.next());
1129         if (result != 0) {
1130           break;
1131         }
1132       }
1133     }
1134     if (result == 0) {
1135       // punt on comparison for ordering, just calculate difference
1136       result = this.values.hashCode() - other.values.hashCode();
1137       if (result < 0)
1138         result = -1;
1139       else if (result > 0)
1140         result = 1;
1141     }
1142     if (result == 0) {
1143       result = this.configuration.hashCode() - other.configuration.hashCode();
1144       if (result < 0)
1145         result = -1;
1146       else if (result > 0)
1147         result = 1;
1148     }
1149     return result;
1150   }
1151 
1152   /**
1153    * Returns an unmodifiable collection of all the {@link HColumnDescriptor}
1154    * of all the column families of the table.
1155    *
1156    * @return Immutable collection of {@link HColumnDescriptor} of all the
1157    * column families.
1158    */
1159   public Collection<HColumnDescriptor> getFamilies() {
1160     return Collections.unmodifiableCollection(this.families.values());
1161   }
1162 
1163   /**
1164    * Returns the configured replicas per region
1165    */
1166   public int getRegionReplication() {
1167     byte[] val = getValue(REGION_REPLICATION_KEY);
1168     if (val == null || val.length == 0) {
1169       return DEFAULT_REGION_REPLICATION;
1170     }
1171     return Integer.parseInt(Bytes.toString(val));
1172   }
1173 
1174   /**
1175    * Sets the number of replicas per region.
1176    * @param regionReplication the replication factor per region
1177    */
1178   public HTableDescriptor setRegionReplication(int regionReplication) {
1179     setValue(REGION_REPLICATION_KEY,
1180         new ImmutableBytesWritable(Bytes.toBytes(Integer.toString(regionReplication))));
1181     return this;
1182   }
1183 
1184   /**
1185    * @return true if the read-replicas memstore replication is enabled.
1186    */
1187   public boolean hasRegionMemstoreReplication() {
1188     return isSomething(REGION_MEMSTORE_REPLICATION_KEY, DEFAULT_REGION_MEMSTORE_REPLICATION);
1189   }
1190 
1191   /**
1192    * Enable or Disable the memstore replication from the primary region to the replicas.
1193    * The replication will be used only for meta operations (e.g. flush, compaction, ...)
1194    *
1195    * @param memstoreReplication true if the new data written to the primary region
1196    *                                 should be replicated.
1197    *                            false if the secondaries can tollerate to have new
1198    *                                  data only when the primary flushes the memstore.
1199    */
1200   public HTableDescriptor setRegionMemstoreReplication(boolean memstoreReplication) {
1201     setValue(REGION_MEMSTORE_REPLICATION_KEY, memstoreReplication ? TRUE : FALSE);
1202     // If the memstore replication is setup, we do not have to wait for observing a flush event
1203     // from primary before starting to serve reads, because gaps from replication is not applicable
1204     setConfiguration(RegionReplicaUtil.REGION_REPLICA_WAIT_FOR_PRIMARY_FLUSH_CONF_KEY,
1205       Boolean.toString(memstoreReplication));
1206     return this;
1207   }
1208 
1209   /**
1210    * Returns all the column family names of the current table. The map of
1211    * HTableDescriptor contains mapping of family name to HColumnDescriptors.
1212    * This returns all the keys of the family map which represents the column
1213    * family names of the table.
1214    *
1215    * @return Immutable sorted set of the keys of the families.
1216    */
1217   public Set<byte[]> getFamiliesKeys() {
1218     return Collections.unmodifiableSet(this.families.keySet());
1219   }
1220 
1221   /**
1222    * Returns an array all the {@link HColumnDescriptor} of the column families
1223    * of the table.
1224    *
1225    * @return Array of all the HColumnDescriptors of the current table
1226    *
1227    * @see #getFamilies()
1228    */
1229   public HColumnDescriptor[] getColumnFamilies() {
1230     Collection<HColumnDescriptor> hColumnDescriptors = getFamilies();
1231     return hColumnDescriptors.toArray(new HColumnDescriptor[hColumnDescriptors.size()]);
1232   }
1233 
1234 
1235   /**
1236    * Returns the HColumnDescriptor for a specific column family with name as
1237    * specified by the parameter column.
1238    *
1239    * @param column Column family name
1240    * @return Column descriptor for the passed family name or the family on
1241    * passed in column.
1242    */
1243   public HColumnDescriptor getFamily(final byte [] column) {
1244     return this.families.get(column);
1245   }
1246 
1247 
1248   /**
1249    * Removes the HColumnDescriptor with name specified by the parameter column
1250    * from the table descriptor
1251    *
1252    * @param column Name of the column family to be removed.
1253    * @return Column descriptor for the passed family name or the family on
1254    * passed in column.
1255    */
1256   public HColumnDescriptor removeFamily(final byte [] column) {
1257     return this.families.remove(column);
1258   }
1259 
1260 
1261   /**
1262    * Add a table coprocessor to this table. The coprocessor
1263    * type must be {@link org.apache.hadoop.hbase.coprocessor.RegionObserver}
1264    * or Endpoint.
1265    * It won't check if the class can be loaded or not.
1266    * Whether a coprocessor is loadable or not will be determined when
1267    * a region is opened.
1268    * @param className Full class name.
1269    * @throws IOException
1270    */
1271   public HTableDescriptor addCoprocessor(String className) throws IOException {
1272     addCoprocessor(className, null, Coprocessor.PRIORITY_USER, null);
1273     return this;
1274   }
1275 
1276 
1277   /**
1278    * Add a table coprocessor to this table. The coprocessor
1279    * type must be {@link org.apache.hadoop.hbase.coprocessor.RegionObserver}
1280    * or Endpoint.
1281    * It won't check if the class can be loaded or not.
1282    * Whether a coprocessor is loadable or not will be determined when
1283    * a region is opened.
1284    * @param jarFilePath Path of the jar file. If it's null, the class will be
1285    * loaded from default classloader.
1286    * @param className Full class name.
1287    * @param priority Priority
1288    * @param kvs Arbitrary key-value parameter pairs passed into the coprocessor.
1289    * @throws IOException
1290    */
1291   public HTableDescriptor addCoprocessor(String className, Path jarFilePath,
1292                              int priority, final Map<String, String> kvs)
1293   throws IOException {
1294     if (hasCoprocessor(className)) {
1295       throw new IOException("Coprocessor " + className + " already exists.");
1296     }
1297     // validate parameter kvs
1298     StringBuilder kvString = new StringBuilder();
1299     if (kvs != null) {
1300       for (Map.Entry<String, String> e: kvs.entrySet()) {
1301         if (!e.getKey().matches(HConstants.CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN)) {
1302           throw new IOException("Illegal parameter key = " + e.getKey());
1303         }
1304         if (!e.getValue().matches(HConstants.CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN)) {
1305           throw new IOException("Illegal parameter (" + e.getKey() +
1306               ") value = " + e.getValue());
1307         }
1308         if (kvString.length() != 0) {
1309           kvString.append(',');
1310         }
1311         kvString.append(e.getKey());
1312         kvString.append('=');
1313         kvString.append(e.getValue());
1314       }
1315     }
1316 
1317     // generate a coprocessor key
1318     int maxCoprocessorNumber = 0;
1319     Matcher keyMatcher;
1320     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1321         this.values.entrySet()) {
1322       keyMatcher =
1323           HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(
1324               Bytes.toString(e.getKey().get()));
1325       if (!keyMatcher.matches()) {
1326         continue;
1327       }
1328       maxCoprocessorNumber = Math.max(Integer.parseInt(keyMatcher.group(1)),
1329           maxCoprocessorNumber);
1330     }
1331     maxCoprocessorNumber++;
1332 
1333     String key = "coprocessor$" + Integer.toString(maxCoprocessorNumber);
1334     String value = ((jarFilePath == null)? "" : jarFilePath.toString()) +
1335         "|" + className + "|" + Integer.toString(priority) + "|" +
1336         kvString.toString();
1337     setValue(key, value);
1338     return this;
1339   }
1340 
1341 
1342   /**
1343    * Check if the table has an attached co-processor represented by the name className
1344    *
1345    * @param className - Class name of the co-processor
1346    * @return true of the table has a co-processor className
1347    */
1348   public boolean hasCoprocessor(String className) {
1349     Matcher keyMatcher;
1350     Matcher valueMatcher;
1351     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1352         this.values.entrySet()) {
1353       keyMatcher =
1354           HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(
1355               Bytes.toString(e.getKey().get()));
1356       if (!keyMatcher.matches()) {
1357         continue;
1358       }
1359       valueMatcher =
1360         HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(
1361             Bytes.toString(e.getValue().get()));
1362       if (!valueMatcher.matches()) {
1363         continue;
1364       }
1365       // get className and compare
1366       String clazz = valueMatcher.group(2).trim(); // classname is the 2nd field
1367       if (clazz.equals(className.trim())) {
1368         return true;
1369       }
1370     }
1371     return false;
1372   }
1373 
1374   /**
1375    * Return the list of attached co-processor represented by their name className
1376    *
1377    * @return The list of co-processors classNames
1378    */
1379   public List<String> getCoprocessors() {
1380     List<String> result = new ArrayList<String>();
1381     Matcher keyMatcher;
1382     Matcher valueMatcher;
1383     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : this.values.entrySet()) {
1384       keyMatcher = HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e.getKey().get()));
1385       if (!keyMatcher.matches()) {
1386         continue;
1387       }
1388       valueMatcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(Bytes
1389           .toString(e.getValue().get()));
1390       if (!valueMatcher.matches()) {
1391         continue;
1392       }
1393       result.add(valueMatcher.group(2).trim()); // classname is the 2nd field
1394     }
1395     return result;
1396   }
1397 
1398   /**
1399    * Remove a coprocessor from those set on the table
1400    * @param className Class name of the co-processor
1401    */
1402   public void removeCoprocessor(String className) {
1403     ImmutableBytesWritable match = null;
1404     Matcher keyMatcher;
1405     Matcher valueMatcher;
1406     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : this.values
1407         .entrySet()) {
1408       keyMatcher = HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e
1409           .getKey().get()));
1410       if (!keyMatcher.matches()) {
1411         continue;
1412       }
1413       valueMatcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(Bytes
1414           .toString(e.getValue().get()));
1415       if (!valueMatcher.matches()) {
1416         continue;
1417       }
1418       // get className and compare
1419       String clazz = valueMatcher.group(2).trim(); // classname is the 2nd field
1420       // remove the CP if it is present
1421       if (clazz.equals(className.trim())) {
1422         match = e.getKey();
1423         break;
1424       }
1425     }
1426     // if we found a match, remove it
1427     if (match != null)
1428       remove(match);
1429   }
1430 
1431   /**
1432    * Returns the {@link Path} object representing the table directory under
1433    * path rootdir
1434    *
1435    * Deprecated use FSUtils.getTableDir() instead.
1436    *
1437    * @param rootdir qualified path of HBase root directory
1438    * @param tableName name of table
1439    * @return {@link Path} for table
1440    */
1441   @Deprecated
1442   public static Path getTableDir(Path rootdir, final byte [] tableName) {
1443     //This is bad I had to mirror code from FSUTils.getTableDir since
1444     //there is no module dependency between hbase-client and hbase-server
1445     TableName name = TableName.valueOf(tableName);
1446     return new Path(rootdir, new Path(HConstants.BASE_NAMESPACE_DIR,
1447               new Path(name.getNamespaceAsString(), new Path(name.getQualifierAsString()))));
1448   }
1449 
1450   /**
1451    * Table descriptor for <code>hbase:meta</code> catalog table
1452    * @deprecated Use TableDescriptors#get(TableName.META_TABLE_NAME) or
1453    * HBaseAdmin#getTableDescriptor(TableName.META_TABLE_NAME) instead.
1454    */
1455   @Deprecated
1456   public static final HTableDescriptor META_TABLEDESC = new HTableDescriptor(
1457       TableName.META_TABLE_NAME,
1458       new HColumnDescriptor[] {
1459           new HColumnDescriptor(HConstants.CATALOG_FAMILY)
1460               // Ten is arbitrary number.  Keep versions to help debugging.
1461               .setMaxVersions(HConstants.DEFAULT_HBASE_META_VERSIONS)
1462               .setInMemory(true)
1463               .setBlocksize(HConstants.DEFAULT_HBASE_META_BLOCK_SIZE)
1464               .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
1465               // Disable blooms for meta.  Needs work.  Seems to mess w/ getClosestOrBefore.
1466               .setBloomFilterType(BloomType.NONE)
1467               // Enable cache of data blocks in L1 if more than one caching tier deployed:
1468               // e.g. if using CombinedBlockCache (BucketCache).
1469               .setCacheDataInL1(true)
1470       });
1471 
1472   static {
1473     try {
1474       META_TABLEDESC.addCoprocessor(
1475           "org.apache.hadoop.hbase.coprocessor.MultiRowMutationEndpoint",
1476           null, Coprocessor.PRIORITY_SYSTEM, null);
1477     } catch (IOException ex) {
1478       //LOG.warn("exception in loading coprocessor for the hbase:meta table");
1479       throw new RuntimeException(ex);
1480     }
1481   }
1482 
1483   public final static String NAMESPACE_FAMILY_INFO = "info";
1484   public final static byte[] NAMESPACE_FAMILY_INFO_BYTES = Bytes.toBytes(NAMESPACE_FAMILY_INFO);
1485   public final static byte[] NAMESPACE_COL_DESC_BYTES = Bytes.toBytes("d");
1486 
1487   /** Table descriptor for namespace table */
1488   public static final HTableDescriptor NAMESPACE_TABLEDESC = new HTableDescriptor(
1489       TableName.NAMESPACE_TABLE_NAME,
1490       new HColumnDescriptor[] {
1491           new HColumnDescriptor(NAMESPACE_FAMILY_INFO)
1492               // Ten is arbitrary number.  Keep versions to help debugging.
1493               .setMaxVersions(10)
1494               .setInMemory(true)
1495               .setBlocksize(8 * 1024)
1496               .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
1497               // Enable cache of data blocks in L1 if more than one caching tier deployed:
1498               // e.g. if using CombinedBlockCache (BucketCache).
1499               .setCacheDataInL1(true)
1500       });
1501 
1502   @Deprecated
1503   public HTableDescriptor setOwner(User owner) {
1504     return setOwnerString(owner != null ? owner.getShortName() : null);
1505   }
1506 
1507   // used by admin.rb:alter(table_name,*args) to update owner.
1508   @Deprecated
1509   public HTableDescriptor setOwnerString(String ownerString) {
1510     if (ownerString != null) {
1511       setValue(OWNER_KEY, ownerString);
1512     } else {
1513       remove(OWNER_KEY);
1514     }
1515     return this;
1516   }
1517 
1518   @Deprecated
1519   public String getOwnerString() {
1520     if (getValue(OWNER_KEY) != null) {
1521       return Bytes.toString(getValue(OWNER_KEY));
1522     }
1523     // Note that every table should have an owner (i.e. should have OWNER_KEY set).
1524     // hbase:meta and -ROOT- should return system user as owner, not null (see
1525     // MasterFileSystem.java:bootstrap()).
1526     return null;
1527   }
1528 
1529   /**
1530    * @return This instance serialized with pb with pb magic prefix
1531    * @see #parseFrom(byte[])
1532    */
1533   public byte [] toByteArray() {
1534     return ProtobufUtil.prependPBMagic(convert().toByteArray());
1535   }
1536 
1537   /**
1538    * @param bytes A pb serialized {@link HTableDescriptor} instance with pb magic prefix
1539    * @return An instance of {@link HTableDescriptor} made from <code>bytes</code>
1540    * @throws DeserializationException
1541    * @throws IOException
1542    * @see #toByteArray()
1543    */
1544   public static HTableDescriptor parseFrom(final byte [] bytes)
1545   throws DeserializationException, IOException {
1546     if (!ProtobufUtil.isPBMagicPrefix(bytes)) {
1547       return (HTableDescriptor)Writables.getWritable(bytes, new HTableDescriptor());
1548     }
1549     int pblen = ProtobufUtil.lengthOfPBMagic();
1550     TableSchema.Builder builder = TableSchema.newBuilder();
1551     TableSchema ts;
1552     try {
1553       ts = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
1554     } catch (InvalidProtocolBufferException e) {
1555       throw new DeserializationException(e);
1556     }
1557     return convert(ts);
1558   }
1559 
1560   /**
1561    * @return Convert the current {@link HTableDescriptor} into a pb TableSchema instance.
1562    */
1563   public TableSchema convert() {
1564     TableSchema.Builder builder = TableSchema.newBuilder();
1565     builder.setTableName(ProtobufUtil.toProtoTableName(getTableName()));
1566     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e: this.values.entrySet()) {
1567       BytesBytesPair.Builder aBuilder = BytesBytesPair.newBuilder();
1568       aBuilder.setFirst(ByteStringer.wrap(e.getKey().get()));
1569       aBuilder.setSecond(ByteStringer.wrap(e.getValue().get()));
1570       builder.addAttributes(aBuilder.build());
1571     }
1572     for (HColumnDescriptor hcd: getColumnFamilies()) {
1573       builder.addColumnFamilies(hcd.convert());
1574     }
1575     for (Map.Entry<String, String> e : this.configuration.entrySet()) {
1576       NameStringPair.Builder aBuilder = NameStringPair.newBuilder();
1577       aBuilder.setName(e.getKey());
1578       aBuilder.setValue(e.getValue());
1579       builder.addConfiguration(aBuilder.build());
1580     }
1581     return builder.build();
1582   }
1583 
1584   /**
1585    * @param ts A pb TableSchema instance.
1586    * @return An {@link HTableDescriptor} made from the passed in pb <code>ts</code>.
1587    */
1588   public static HTableDescriptor convert(final TableSchema ts) {
1589     List<ColumnFamilySchema> list = ts.getColumnFamiliesList();
1590     HColumnDescriptor [] hcds = new HColumnDescriptor[list.size()];
1591     int index = 0;
1592     for (ColumnFamilySchema cfs: list) {
1593       hcds[index++] = HColumnDescriptor.convert(cfs);
1594     }
1595     HTableDescriptor htd = new HTableDescriptor(
1596         ProtobufUtil.toTableName(ts.getTableName()),
1597         hcds);
1598     for (BytesBytesPair a: ts.getAttributesList()) {
1599       htd.setValue(a.getFirst().toByteArray(), a.getSecond().toByteArray());
1600     }
1601     for (NameStringPair a: ts.getConfigurationList()) {
1602       htd.setConfiguration(a.getName(), a.getValue());
1603     }
1604     return htd;
1605   }
1606 
1607   /**
1608    * Getter for accessing the configuration value by key
1609    */
1610   public String getConfigurationValue(String key) {
1611     return configuration.get(key);
1612   }
1613 
1614   /**
1615    * Getter for fetching an unmodifiable {@link #configuration} map.
1616    */
1617   public Map<String, String> getConfiguration() {
1618     // shallow pointer copy
1619     return Collections.unmodifiableMap(configuration);
1620   }
1621 
1622   /**
1623    * Setter for storing a configuration setting in {@link #configuration} map.
1624    * @param key Config key. Same as XML config key e.g. hbase.something.or.other.
1625    * @param value String value. If null, removes the setting.
1626    */
1627   public HTableDescriptor setConfiguration(String key, String value) {
1628     if (value == null) {
1629       removeConfiguration(key);
1630     } else {
1631       configuration.put(key, value);
1632     }
1633     return this;
1634   }
1635 
1636   /**
1637    * Remove a config setting represented by the key from the {@link #configuration} map
1638    */
1639   public void removeConfiguration(final String key) {
1640     configuration.remove(key);
1641   }
1642 
1643   public static HTableDescriptor metaTableDescriptor(final Configuration conf)
1644       throws IOException {
1645     HTableDescriptor metaDescriptor = new HTableDescriptor(
1646       TableName.META_TABLE_NAME,
1647       new HColumnDescriptor[] {
1648         new HColumnDescriptor(HConstants.CATALOG_FAMILY)
1649           .setMaxVersions(conf.getInt(HConstants.HBASE_META_VERSIONS,
1650             HConstants.DEFAULT_HBASE_META_VERSIONS))
1651           .setInMemory(true)
1652           .setBlocksize(conf.getInt(HConstants.HBASE_META_BLOCK_SIZE,
1653             HConstants.DEFAULT_HBASE_META_BLOCK_SIZE))
1654           .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
1655           // Disable blooms for meta.  Needs work.  Seems to mess w/ getClosestOrBefore.
1656           .setBloomFilterType(BloomType.NONE)
1657          });
1658     metaDescriptor.addCoprocessor(
1659       "org.apache.hadoop.hbase.coprocessor.MultiRowMutationEndpoint",
1660       null, Coprocessor.PRIORITY_SYSTEM, null);
1661     return metaDescriptor;
1662   }
1663 
1664 }