View Javadoc

1   /**
2    * Copyright 2009 The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase;
21  
22  import java.io.DataInput;
23  import java.io.DataOutput;
24  import java.io.IOException;
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.Collections;
28  import java.util.HashMap;
29  import java.util.Iterator;
30  import java.util.List;
31  import java.util.Map;
32  import java.util.Set;
33  import java.util.HashSet;
34  import java.util.TreeSet;
35  import java.util.TreeMap;
36  import java.util.regex.Matcher;
37  
38  import org.apache.hadoop.conf.Configuration;
39  import org.apache.hadoop.fs.Path;
40  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
41  import org.apache.hadoop.hbase.security.User;
42  import org.apache.hadoop.hbase.util.Bytes;
43  import org.apache.hadoop.io.WritableComparable;
44  
45  /**
46   * HTableDescriptor contains the details about an HBase table  such as the descriptors of
47   * all the column families, is the table a catalog table, <code> -ROOT- </code> or 
48   * <code> .META. </code>, is the table is read only, the maximum size of the memstore, 
49   * when the region split should occur, coprocessors associated with it etc...
50   */
51  public class HTableDescriptor implements WritableComparable<HTableDescriptor> {
52  
53    /**
54     *  Changes prior to version 3 were not recorded here.
55     *  Version 3 adds metadata as a map where keys and values are byte[].
56     *  Version 4 adds indexes
57     *  Version 5 removed transactional pollution -- e.g. indexes
58     */
59    private static final byte TABLE_DESCRIPTOR_VERSION = 5;
60  
61    private byte [] name = HConstants.EMPTY_BYTE_ARRAY;
62  
63    private String nameAsString = "";
64  
65    /**
66     * A map which holds the metadata information of the table. This metadata 
67     * includes values like IS_ROOT, IS_META, DEFERRED_LOG_FLUSH, SPLIT_POLICY,
68     * MAX_FILE_SIZE, READONLY, MEMSTORE_FLUSHSIZE etc...
69     */
70    protected final Map<ImmutableBytesWritable, ImmutableBytesWritable> values =
71      new HashMap<ImmutableBytesWritable, ImmutableBytesWritable>();
72  
73    private static final String FAMILIES = "FAMILIES";
74  
75    public static final String SPLIT_POLICY = "SPLIT_POLICY";
76    
77    /**
78     * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata 
79     * attribute which denotes the maximum size of the store file after which 
80     * a region split occurs
81     * 
82     * @see #getMaxFileSize()
83     */
84    public static final String MAX_FILESIZE = "MAX_FILESIZE";
85    private static final ImmutableBytesWritable MAX_FILESIZE_KEY =
86      new ImmutableBytesWritable(Bytes.toBytes(MAX_FILESIZE));
87  
88    public static final String OWNER = "OWNER";
89    public static final ImmutableBytesWritable OWNER_KEY =
90      new ImmutableBytesWritable(Bytes.toBytes(OWNER));
91  
92    /**
93     * <em>INTERNAL</em> Used by rest interface to access this metadata 
94     * attribute which denotes if the table is Read Only
95     * 
96     * @see #isReadOnly()
97     */
98    public static final String READONLY = "READONLY";
99    private static final ImmutableBytesWritable READONLY_KEY =
100     new ImmutableBytesWritable(Bytes.toBytes(READONLY));
101 
102   /**
103    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata 
104    * attribute which represents the maximum size of the memstore after which 
105    * its contents are flushed onto the disk
106    * 
107    * @see #getMemStoreFlushSize()
108    */
109   public static final String MEMSTORE_FLUSHSIZE = "MEMSTORE_FLUSHSIZE";
110   private static final ImmutableBytesWritable MEMSTORE_FLUSHSIZE_KEY =
111     new ImmutableBytesWritable(Bytes.toBytes(MEMSTORE_FLUSHSIZE));
112 
113   /**
114    * <em>INTERNAL</em> Used by rest interface to access this metadata 
115    * attribute which denotes if the table is a -ROOT- region or not
116    * 
117    * @see #isRootRegion()
118    */
119   public static final String IS_ROOT = "IS_ROOT";
120   private static final ImmutableBytesWritable IS_ROOT_KEY =
121     new ImmutableBytesWritable(Bytes.toBytes(IS_ROOT));
122 
123   /**
124    * <em>INTERNAL</em> Used by rest interface to access this metadata 
125    * attribute which denotes if it is a catalog table, either
126    * <code> .META. </code> or <code> -ROOT- </code>
127    * 
128    * @see #isMetaRegion()
129    */
130   public static final String IS_META = "IS_META";
131   private static final ImmutableBytesWritable IS_META_KEY =
132     new ImmutableBytesWritable(Bytes.toBytes(IS_META));
133 
134   /**
135    * <em>INTERNAL</em> Used by HBase Shell interface to access this metadata 
136    * attribute which denotes if the deferred log flush option is enabled
137    */
138   public static final String DEFERRED_LOG_FLUSH = "DEFERRED_LOG_FLUSH";
139   private static final ImmutableBytesWritable DEFERRED_LOG_FLUSH_KEY =
140     new ImmutableBytesWritable(Bytes.toBytes(DEFERRED_LOG_FLUSH));
141 
142   /*
143    *  The below are ugly but better than creating them each time till we
144    *  replace booleans being saved as Strings with plain booleans.  Need a
145    *  migration script to do this.  TODO.
146    */
147   private static final ImmutableBytesWritable FALSE =
148     new ImmutableBytesWritable(Bytes.toBytes(Boolean.FALSE.toString()));
149 
150   private static final ImmutableBytesWritable TRUE =
151     new ImmutableBytesWritable(Bytes.toBytes(Boolean.TRUE.toString()));
152 
153   private static final boolean DEFAULT_DEFERRED_LOG_FLUSH = false;
154   
155   /**
156    * Constant that denotes whether the table is READONLY by default and is false
157    */
158   public static final boolean DEFAULT_READONLY = false;
159 
160   /**
161    * Constant that denotes the maximum default size of the memstore after which 
162    * the contents are flushed to the store files
163    */
164   public static final long DEFAULT_MEMSTORE_FLUSH_SIZE = 1024*1024*128L;
165   private final static Map<String, String> DEFAULT_VALUES
166     = new HashMap<String, String>();
167   private final static Set<ImmutableBytesWritable> RESERVED_KEYWORDS
168     = new HashSet<ImmutableBytesWritable>();
169   static {
170     DEFAULT_VALUES.put(MAX_FILESIZE,
171         String.valueOf(HConstants.DEFAULT_MAX_FILE_SIZE));
172     DEFAULT_VALUES.put(READONLY, String.valueOf(DEFAULT_READONLY));
173     DEFAULT_VALUES.put(MEMSTORE_FLUSHSIZE,
174         String.valueOf(DEFAULT_MEMSTORE_FLUSH_SIZE));
175     DEFAULT_VALUES.put(DEFERRED_LOG_FLUSH,
176         String.valueOf(DEFAULT_DEFERRED_LOG_FLUSH));
177     for (String s : DEFAULT_VALUES.keySet()) {
178       RESERVED_KEYWORDS.add(new ImmutableBytesWritable(Bytes.toBytes(s)));
179     }
180     RESERVED_KEYWORDS.add(IS_ROOT_KEY);
181     RESERVED_KEYWORDS.add(IS_META_KEY);
182   }
183 
184   
185 
186   private volatile Boolean meta = null;
187   private volatile Boolean root = null;
188   private Boolean isDeferredLog = null;
189 
190   /**
191    * Maps column family name to the respective HColumnDescriptors
192    */
193   private final Map<byte [], HColumnDescriptor> families =
194     new TreeMap<byte [], HColumnDescriptor>(Bytes.BYTES_RAWCOMPARATOR);
195 
196   /**
197    * <em> INTERNAL </em> Private constructor used internally creating table descriptors for
198    * catalog tables, <code>.META.</code> and <code>-ROOT-</code>.
199    */
200   protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families) {
201     this.name = name.clone();
202     this.nameAsString = Bytes.toString(this.name);
203     setMetaFlags(name);
204     for(HColumnDescriptor descriptor : families) {
205       this.families.put(descriptor.getName(), descriptor);
206     }
207   }
208 
209   /**
210    * <em> INTERNAL </em>Private constructor used internally creating table descriptors for
211    * catalog tables, <code>.META.</code> and <code>-ROOT-</code>.
212    */
213   protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families,
214       Map<ImmutableBytesWritable,ImmutableBytesWritable> values) {
215     this.name = name.clone();
216     this.nameAsString = Bytes.toString(this.name);
217     setMetaFlags(name);
218     for(HColumnDescriptor descriptor : families) {
219       this.families.put(descriptor.getName(), descriptor);
220     }
221     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> entry:
222         values.entrySet()) {
223       this.values.put(entry.getKey(), entry.getValue());
224     }
225   }
226 
227   /**
228    * Default constructor which constructs an empty object.
229    * For deserializing an HTableDescriptor instance only.
230    * @see #HTableDescriptor(byte[])
231    */
232   public HTableDescriptor() {
233     super();
234   }
235 
236   /**
237    * Construct a table descriptor specifying table name.
238    * @param name Table name.
239    * @throws IllegalArgumentException if passed a table name
240    * that is made of other than 'word' characters, underscore or period: i.e.
241    * <code>[a-zA-Z_0-9.].
242    * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
243    */
244   public HTableDescriptor(final String name) {
245     this(Bytes.toBytes(name));
246   }
247 
248   /**
249    * Construct a table descriptor specifying a byte array table name
250    * @param name - Table name as a byte array.
251    * @throws IllegalArgumentException if passed a table name
252    * that is made of other than 'word' characters, underscore or period: i.e.
253    * <code>[a-zA-Z_0-9-.].
254    * @see <a href="HADOOP-1581">HADOOP-1581 HBASE: Un-openable tablename bug</a>
255    */
256   public HTableDescriptor(final byte [] name) {
257     super();
258     setMetaFlags(this.name);
259     this.name = this.isMetaRegion()? name: isLegalTableName(name);
260     this.nameAsString = Bytes.toString(this.name);
261   }
262 
263   /**
264    * Construct a table descriptor by cloning the descriptor passed as a parameter.
265    * <p>
266    * Makes a deep copy of the supplied descriptor.
267    * Can make a modifiable descriptor from an UnmodifyableHTableDescriptor.
268    * @param desc The descriptor.
269    */
270   public HTableDescriptor(final HTableDescriptor desc) {
271     super();
272     this.name = desc.name.clone();
273     this.nameAsString = Bytes.toString(this.name);
274     setMetaFlags(this.name);
275     for (HColumnDescriptor c: desc.families.values()) {
276       this.families.put(c.getName(), new HColumnDescriptor(c));
277     }
278     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
279         desc.values.entrySet()) {
280       this.values.put(e.getKey(), e.getValue());
281     }
282   }
283 
284   /*
285    * Set meta flags on this table. 
286    * IS_ROOT_KEY is set if its a -ROOT- table
287    * IS_META_KEY is set either if its a -ROOT- or a .META. table 
288    * Called by constructors.
289    * @param name
290    */
291   private void setMetaFlags(final byte [] name) {
292     setRootRegion(Bytes.equals(name, HConstants.ROOT_TABLE_NAME));
293     setMetaRegion(isRootRegion() ||
294       Bytes.equals(name, HConstants.META_TABLE_NAME));
295   }
296 
297   /**
298    * Check if the descriptor represents a <code> -ROOT- </code> region.
299    * 
300    * @return true if this is a <code> -ROOT- </code> region 
301    */
302   public boolean isRootRegion() {
303     if (this.root == null) {
304       this.root = isSomething(IS_ROOT_KEY, false)? Boolean.TRUE: Boolean.FALSE;
305     }
306     return this.root.booleanValue();
307   }
308 
309   /**
310    * <em> INTERNAL </em> Used to denote if the current table represents 
311    * <code> -ROOT- </code> region. This is used internally by the 
312    * HTableDescriptor constructors 
313    * 
314    * @param isRoot true if this is the <code> -ROOT- </code> region 
315    */
316   protected void setRootRegion(boolean isRoot) {
317     // TODO: Make the value a boolean rather than String of boolean.
318     values.put(IS_ROOT_KEY, isRoot? TRUE: FALSE);
319   }
320 
321   /**
322    * Checks if this table is either <code> -ROOT- </code> or <code> .META. </code>
323    * region. 
324    *  
325    * @return true if this is either a <code> -ROOT- </code> or <code> .META. </code> 
326    * region 
327    */
328   public boolean isMetaRegion() {
329     if (this.meta == null) {
330       this.meta = calculateIsMetaRegion();
331     }
332     return this.meta.booleanValue();
333   }
334 
335   private synchronized Boolean calculateIsMetaRegion() {
336     byte [] value = getValue(IS_META_KEY);
337     return (value != null)? Boolean.valueOf(Bytes.toString(value)): Boolean.FALSE;
338   }
339 
340   private boolean isSomething(final ImmutableBytesWritable key,
341       final boolean valueIfNull) {
342     byte [] value = getValue(key);
343     if (value != null) {
344       // TODO: Make value be a boolean rather than String of boolean.
345       return Boolean.valueOf(Bytes.toString(value)).booleanValue();
346     }
347     return valueIfNull;
348   }
349 
350   /**
351    * <em> INTERNAL </em> Used to denote if the current table represents 
352    * <code> -ROOT- </code> or <code> .META. </code> region. This is used 
353    * internally by the HTableDescriptor constructors 
354    * 
355    * @param isMeta true if its either <code> -ROOT- </code> or 
356    * <code> .META. </code> region 
357    */
358   protected void setMetaRegion(boolean isMeta) {
359     values.put(IS_META_KEY, isMeta? TRUE: FALSE);
360   }
361 
362   /** 
363    * Checks if the table is a <code>.META.</code> table 
364    *  
365    * @return true if table is <code> .META. </code> region.
366    */
367   public boolean isMetaTable() {
368     return isMetaRegion() && !isRootRegion();
369   }
370  
371   /**
372    * Checks of the tableName being passed represents either 
373    * <code > -ROOT- </code> or <code> .META. </code>
374    *  
375    * @return true if a tablesName is either <code> -ROOT- </code> 
376    * or <code> .META. </code>
377    */
378   public static boolean isMetaTable(final byte [] tableName) {
379     return Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME) ||
380       Bytes.equals(tableName, HConstants.META_TABLE_NAME);
381   }
382 
383   // A non-capture group so that this can be embedded.
384   public static final String VALID_USER_TABLE_REGEX = "(?:[a-zA-Z_0-9][a-zA-Z_0-9.-]*)";
385 
386   /**
387    * Check passed byte buffer, "tableName", is legal user-space table name.
388    * @return Returns passed <code>tableName</code> param
389    * @throws NullPointerException If passed <code>tableName</code> is null
390    * @throws IllegalArgumentException if passed a tableName
391    * that is made of other than 'word' characters or underscores: i.e.
392    * <code>[a-zA-Z_0-9].
393    */
394   public static byte [] isLegalTableName(final byte [] tableName) {
395     if (tableName == null || tableName.length <= 0) {
396       throw new IllegalArgumentException("Name is null or empty");
397     }
398     if (tableName[0] == '.' || tableName[0] == '-') {
399       throw new IllegalArgumentException("Illegal first character <" + tableName[0] +
400           "> at 0. User-space table names can only start with 'word " +
401           "characters': i.e. [a-zA-Z_0-9]: " + Bytes.toString(tableName));
402     }
403     for (int i = 0; i < tableName.length; i++) {
404       if (Character.isLetterOrDigit(tableName[i]) || tableName[i] == '_' || 
405     		  tableName[i] == '-' || tableName[i] == '.') {
406         continue;
407       }
408       throw new IllegalArgumentException("Illegal character <" + tableName[i] +
409         "> at " + i + ". User-space table names can only contain " +
410         "'word characters': i.e. [a-zA-Z_0-9-.]: " + Bytes.toString(tableName));
411     }
412     return tableName;
413   }
414 
415   /**
416    * Getter for accessing the metadata associated with the key
417    *  
418    * @param key The key.
419    * @return The value.
420    * @see #values
421    */
422   public byte[] getValue(byte[] key) {
423     return getValue(new ImmutableBytesWritable(key));
424   }
425 
426   private byte[] getValue(final ImmutableBytesWritable key) {
427     ImmutableBytesWritable ibw = values.get(key);
428     if (ibw == null)
429       return null;
430     return ibw.get();
431   }
432 
433   /**
434    * Getter for accessing the metadata associated with the key
435    *  
436    * @param key The key.
437    * @return The value.
438    * @see #values
439    */
440   public String getValue(String key) {
441     byte[] value = getValue(Bytes.toBytes(key));
442     if (value == null)
443       return null;
444     return Bytes.toString(value);
445   }
446 
447   /**
448    * Getter for fetching an unmodifiable {@link #values} map.
449    *  
450    * @return unmodifiable map {@link #values}.
451    * @see #values
452    */
453   public Map<ImmutableBytesWritable,ImmutableBytesWritable> getValues() {
454     // shallow pointer copy 
455     return Collections.unmodifiableMap(values);
456   }
457 
458   /**
459    * Setter for storing metadata as a (key, value) pair in {@link #values} map
460    *  
461    * @param key The key.
462    * @param value The value.
463    * @see #values
464    */
465   public void setValue(byte[] key, byte[] value) {
466     setValue(new ImmutableBytesWritable(key), value);
467   }
468 
469   /*
470    * @param key The key.
471    * @param value The value.
472    */
473   private void setValue(final ImmutableBytesWritable key,
474       final byte[] value) {
475     values.put(key, new ImmutableBytesWritable(value));
476   }
477 
478   /*
479    * Setter for storing metadata as a (key, value) pair in {@link #values} map
480    *
481    * @param key The key.
482    * @param value The value.
483    */
484   public void setValue(final ImmutableBytesWritable key,
485       final ImmutableBytesWritable value) {
486     values.put(key, value);
487   }
488 
489   /**
490    * Setter for storing metadata as a (key, value) pair in {@link #values} map
491    *  
492    * @param key The key.
493    * @param value The value.
494    * @see #values
495    */
496   public void setValue(String key, String value) {
497     if (value == null) {
498       remove(Bytes.toBytes(key));
499     } else {
500       setValue(Bytes.toBytes(key), Bytes.toBytes(value));
501     }
502   }
503 
504   /**
505    * Remove metadata represented by the key from the {@link #values} map
506    * 
507    * @param key Key whose key and value we're to remove from HTableDescriptor
508    * parameters.
509    */
510   public void remove(final byte [] key) {
511     values.remove(new ImmutableBytesWritable(key));
512   }
513   
514   /**
515    * Remove metadata represented by the key from the {@link #values} map
516    * 
517    * @param key Key whose key and value we're to remove from HTableDescriptor
518    * parameters.
519    */
520   public void remove(final String key) {
521     remove(Bytes.toBytes(key));
522   }
523 
524   /**
525    * Check if the readOnly flag of the table is set. If the readOnly flag is 
526    * set then the contents of the table can only be read from but not modified.
527    * 
528    * @return true if all columns in the table should be read only
529    */
530   public boolean isReadOnly() {
531     return isSomething(READONLY_KEY, DEFAULT_READONLY);
532   }
533 
534   /**
535    * Setting the table as read only sets all the columns in the table as read
536    * only. By default all tables are modifiable, but if the readOnly flag is 
537    * set to true then the contents of the table can only be read but not modified.
538    *  
539    * @param readOnly True if all of the columns in the table should be read
540    * only.
541    */
542   public void setReadOnly(final boolean readOnly) {
543     setValue(READONLY_KEY, readOnly? TRUE: FALSE);
544   }
545 
546   /**
547    * Check if deferred log edits are enabled on the table.  
548    * 
549    * @return true if that deferred log flush is enabled on the table
550    * 
551    * @see #setDeferredLogFlush(boolean)
552    */
553   public synchronized boolean isDeferredLogFlush() {
554     if(this.isDeferredLog == null) {
555       this.isDeferredLog =
556           isSomething(DEFERRED_LOG_FLUSH_KEY, DEFAULT_DEFERRED_LOG_FLUSH);
557     }
558     return this.isDeferredLog;
559   }
560 
561   /**
562    * This is used to defer the log edits syncing to the file system. Everytime 
563    * an edit is sent to the server it is first sync'd to the file system by the 
564    * log writer. This sync is an expensive operation and thus can be deferred so 
565    * that the edits are kept in memory for a specified period of time as represented
566    * by <code> hbase.regionserver.optionallogflushinterval </code> and not flushed
567    * for every edit.
568    * <p>
569    * NOTE:- This option might result in data loss if the region server crashes
570    * before these deferred edits in memory are flushed onto the filesystem. 
571    * </p>
572    * 
573    * @param isDeferredLogFlush
574    */
575   public void setDeferredLogFlush(final boolean isDeferredLogFlush) {
576     setValue(DEFERRED_LOG_FLUSH_KEY, isDeferredLogFlush? TRUE: FALSE);
577     this.isDeferredLog = isDeferredLogFlush;
578   }
579 
580   /**
581    * Get the name of the table as a byte array.
582    * 
583    * @return name of table 
584    */
585   public byte [] getName() {
586     return name;
587   }
588 
589   /**
590    * Get the name of the table as a String
591    * 
592    * @return name of table as a String 
593    */
594   public String getNameAsString() {
595     return this.nameAsString;
596   }
597   
598   /**
599    * This get the class associated with the region split policy which 
600    * determines when a region split should occur.  The class used by
601    * default is {@link org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy}
602    * which split the region base on a constant {@link #getMaxFileSize()}
603    * 
604    * @return the class name of the region split policy for this table.
605    * If this returns null, the default constant size based split policy
606    * is used.
607    */
608    public String getRegionSplitPolicyClassName() {
609     return getValue(SPLIT_POLICY);
610   }
611 
612   /**
613    * Set the name of the table. 
614    * 
615    * @param name name of table 
616    */
617   public void setName(byte[] name) {
618     this.name = name;
619     this.nameAsString = Bytes.toString(this.name);
620     setMetaFlags(this.name);
621   }
622 
623   /** 
624    * Returns the maximum size upto which a region can grow to after which a region
625    * split is triggered. The region size is represented by the size of the biggest
626    * store file in that region.
627    *
628    * @return max hregion size for table, -1 if not set.
629    *
630    * @see #setMaxFileSize(long)
631    */
632   public long getMaxFileSize() {
633     byte [] value = getValue(MAX_FILESIZE_KEY);
634     if (value != null) {
635       return Long.parseLong(Bytes.toString(value));
636     }
637     return -1;
638   }
639 
640   /**
641    * Sets the maximum size upto which a region can grow to after which a region
642    * split is triggered. The region size is represented by the size of the biggest 
643    * store file in that region, i.e. If the biggest store file grows beyond the 
644    * maxFileSize, then the region split is triggered. This defaults to a value of 
645    * 256 MB.
646    * <p>
647    * This is not an absolute value and might vary. Assume that a single row exceeds 
648    * the maxFileSize then the storeFileSize will be greater than maxFileSize since
649    * a single row cannot be split across multiple regions 
650    * </p>
651    * 
652    * @param maxFileSize The maximum file size that a store file can grow to
653    * before a split is triggered.
654    */
655   public void setMaxFileSize(long maxFileSize) {
656     setValue(MAX_FILESIZE_KEY, Bytes.toBytes(Long.toString(maxFileSize)));
657   }
658 
659   /**
660    * Returns the size of the memstore after which a flush to filesystem is triggered.
661    *
662    * @return memory cache flush size for each hregion, -1 if not set.
663    *
664    * @see #setMemStoreFlushSize(long)
665    */
666   public long getMemStoreFlushSize() {
667     byte [] value = getValue(MEMSTORE_FLUSHSIZE_KEY);
668     if (value != null) {
669       return Long.parseLong(Bytes.toString(value));
670     }
671     return -1;
672   }
673 
674   /**
675    * Represents the maximum size of the memstore after which the contents of the 
676    * memstore are flushed to the filesystem. This defaults to a size of 64 MB.
677    * 
678    * @param memstoreFlushSize memory cache flush size for each hregion
679    */
680   public void setMemStoreFlushSize(long memstoreFlushSize) {
681     setValue(MEMSTORE_FLUSHSIZE_KEY,
682       Bytes.toBytes(Long.toString(memstoreFlushSize)));
683   }
684 
685   /**
686    * Adds a column family.
687    * @param family HColumnDescriptor of family to add.
688    */
689   public void addFamily(final HColumnDescriptor family) {
690     if (family.getName() == null || family.getName().length <= 0) {
691       throw new NullPointerException("Family name cannot be null or empty");
692     }
693     this.families.put(family.getName(), family);
694   }
695 
696   /**
697    * Checks to see if this table contains the given column family
698    * @param familyName Family name or column name.
699    * @return true if the table contains the specified family name
700    */
701   public boolean hasFamily(final byte [] familyName) {
702     return families.containsKey(familyName);
703   }
704 
705   /**
706    * @return Name of this table and then a map of all of the column family
707    * descriptors.
708    * @see #getNameAsString()
709    */
710   @Override
711   public String toString() {
712     StringBuilder s = new StringBuilder();
713     s.append('\'').append(Bytes.toString(name)).append('\'');
714     s.append(getValues(true));
715     for (HColumnDescriptor f : families.values()) {
716       s.append(", ").append(f);
717     }
718     return s.toString();
719   }
720 
721   /**
722    * @return Name of this table and then a map of all of the column family
723    * descriptors (with only the non-default column family attributes)
724    */
725   public String toStringCustomizedValues() {
726     StringBuilder s = new StringBuilder();
727     s.append('\'').append(Bytes.toString(name)).append('\'');
728     s.append(getValues(false));
729     for(HColumnDescriptor hcd : families.values()) {
730       s.append(", ").append(hcd.toStringCustomizedValues());
731     }
732     return s.toString();
733   }
734 
735   private StringBuilder getValues(boolean printDefaults) {
736     StringBuilder s = new StringBuilder();
737 
738     // step 1: set partitioning and pruning
739     Set<ImmutableBytesWritable> reservedKeys = new TreeSet<ImmutableBytesWritable>();
740     Set<ImmutableBytesWritable> configKeys = new TreeSet<ImmutableBytesWritable>();
741     for (ImmutableBytesWritable k : values.keySet()) {
742       if (k == null || k.get() == null) continue;
743       String key = Bytes.toString(k.get());
744       // in this section, print out reserved keywords + coprocessor info
745       if (!RESERVED_KEYWORDS.contains(k) && !key.startsWith("coprocessor$")) {
746         configKeys.add(k);        
747         continue;
748       }
749       // only print out IS_ROOT/IS_META if true
750       String value = Bytes.toString(values.get(k).get());
751       if (key.equalsIgnoreCase(IS_ROOT) || key.equalsIgnoreCase(IS_META)) {
752         // Skip. Don't bother printing out read-only values if false.
753         if (value.toLowerCase().equals(Boolean.FALSE.toString())) {
754           continue;
755         }
756       }
757 
758       // see if a reserved key is a default value. may not want to print it out
759       if (printDefaults
760           || !DEFAULT_VALUES.containsKey(key)
761           || !DEFAULT_VALUES.get(key).equalsIgnoreCase(value)) {
762         reservedKeys.add(k);
763       }
764     }
765 
766 
767 
768     // early exit optimization
769     if (reservedKeys.isEmpty() && configKeys.isEmpty()) return s;
770 
771     // step 2: printing
772     s.append(", {METHOD => 'table_att'");
773 
774     // print all reserved keys first
775     for (ImmutableBytesWritable k : reservedKeys) {
776       String key = Bytes.toString(k.get());
777       String value = Bytes.toString(values.get(k).get());
778 
779       s.append(", ");
780       s.append(key);
781       s.append(" => ");
782       s.append('\'').append(value).append('\'');
783     }
784     if (!configKeys.isEmpty()) {
785       // print all non-reserved, advanced config keys as a separate subset
786       s.append(", ");
787       s.append(HConstants.CONFIG).append(" => ");
788       s.append("{");
789       boolean printComma = false;
790       for (ImmutableBytesWritable k : configKeys) {
791         String key = Bytes.toString(k.get());
792         String value = Bytes.toString(values.get(k).get());
793         if (printComma) s.append(", ");
794         printComma = true;
795         s.append('\'').append(key).append('\'');
796         s.append(" => ");
797         s.append('\'').append(value).append('\'');
798       }
799       s.append("}");
800     }
801 
802     s.append('}'); // end METHOD
803     return s;
804   }
805                 
806   public static Map<String, String> getDefaultValues() {
807     return Collections.unmodifiableMap(DEFAULT_VALUES);
808   }
809 
810   /**
811    * Compare the contents of the descriptor with another one passed as a parameter. 
812    * Checks if the obj passed is an instance of HTableDescriptor, if yes then the
813    * contents of the descriptors are compared.
814    * 
815    * @return true if the contents of the the two descriptors exactly match
816    * 
817    * @see java.lang.Object#equals(java.lang.Object)
818    */
819   @Override
820   public boolean equals(Object obj) {
821     if (this == obj) {
822       return true;
823     }
824     if (obj == null) {
825       return false;
826     }
827     if (!(obj instanceof HTableDescriptor)) {
828       return false;
829     }
830     return compareTo((HTableDescriptor)obj) == 0;
831   }
832 
833   /**
834    * @see java.lang.Object#hashCode()
835    */
836   @Override
837   public int hashCode() {
838     int result = Bytes.hashCode(this.name);
839     result ^= Byte.valueOf(TABLE_DESCRIPTOR_VERSION).hashCode();
840     if (this.families != null && this.families.size() > 0) {
841       for (HColumnDescriptor e: this.families.values()) {
842         result ^= e.hashCode();
843       }
844     }
845     result ^= values.hashCode();
846     return result;
847   }
848 
849   // Writable
850   /**
851    * <em> INTERNAL </em> This method is a part of {@link WritableComparable} interface 
852    * and is used for de-serialization of the HTableDescriptor over RPC
853    */
854   @Override
855   public void readFields(DataInput in) throws IOException {
856     int version = in.readInt();
857     if (version < 3)
858       throw new IOException("versions < 3 are not supported (and never existed!?)");
859     // version 3+
860     name = Bytes.readByteArray(in);
861     nameAsString = Bytes.toString(this.name);
862     setRootRegion(in.readBoolean());
863     setMetaRegion(in.readBoolean());
864     values.clear();
865     int numVals = in.readInt();
866     for (int i = 0; i < numVals; i++) {
867       ImmutableBytesWritable key = new ImmutableBytesWritable();
868       ImmutableBytesWritable value = new ImmutableBytesWritable();
869       key.readFields(in);
870       value.readFields(in);
871       values.put(key, value);
872     }
873     families.clear();
874     int numFamilies = in.readInt();
875     for (int i = 0; i < numFamilies; i++) {
876       HColumnDescriptor c = new HColumnDescriptor();
877       c.readFields(in);
878       families.put(c.getName(), c);
879     }
880     if (version < 4) {
881       return;
882     }
883   }
884 
885   /**
886    * <em> INTERNAL </em> This method is a part of {@link WritableComparable} interface 
887    * and is used for serialization of the HTableDescriptor over RPC
888    */
889   @Override
890   public void write(DataOutput out) throws IOException {
891 	out.writeInt(TABLE_DESCRIPTOR_VERSION);
892     Bytes.writeByteArray(out, name);
893     out.writeBoolean(isRootRegion());
894     out.writeBoolean(isMetaRegion());
895     out.writeInt(values.size());
896     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
897         values.entrySet()) {
898       e.getKey().write(out);
899       e.getValue().write(out);
900     }
901     out.writeInt(families.size());
902     for(Iterator<HColumnDescriptor> it = families.values().iterator();
903         it.hasNext(); ) {
904       HColumnDescriptor family = it.next();
905       family.write(out);
906     }
907   }
908 
909   // Comparable
910 
911   /**
912    * Compares the descriptor with another descriptor which is passed as a parameter.
913    * This compares the content of the two descriptors and not the reference.
914    * 
915    * @return 0 if the contents of the descriptors are exactly matching, 
916    * 		 1 if there is a mismatch in the contents 
917    */
918   @Override
919   public int compareTo(final HTableDescriptor other) {
920     int result = Bytes.compareTo(this.name, other.name);
921     if (result == 0) {
922       result = families.size() - other.families.size();
923     }
924     if (result == 0 && families.size() != other.families.size()) {
925       result = Integer.valueOf(families.size()).compareTo(
926           Integer.valueOf(other.families.size()));
927     }
928     if (result == 0) {
929       for (Iterator<HColumnDescriptor> it = families.values().iterator(),
930           it2 = other.families.values().iterator(); it.hasNext(); ) {
931         result = it.next().compareTo(it2.next());
932         if (result != 0) {
933           break;
934         }
935       }
936     }
937     if (result == 0) {
938       // punt on comparison for ordering, just calculate difference
939       result = this.values.hashCode() - other.values.hashCode();
940       if (result < 0)
941         result = -1;
942       else if (result > 0)
943         result = 1;
944     }
945     return result;
946   }
947 
948   /**
949    * Returns an unmodifiable collection of all the {@link HColumnDescriptor} 
950    * of all the column families of the table.
951    *  
952    * @return Immutable collection of {@link HColumnDescriptor} of all the
953    * column families. 
954    */
955   public Collection<HColumnDescriptor> getFamilies() {
956     return Collections.unmodifiableCollection(this.families.values());
957   }
958 
959   /**
960    * Returns all the column family names of the current table. The map of 
961    * HTableDescriptor contains mapping of family name to HColumnDescriptors. 
962    * This returns all the keys of the family map which represents the column 
963    * family names of the table. 
964    * 
965    * @return Immutable sorted set of the keys of the families.
966    */
967   public Set<byte[]> getFamiliesKeys() {
968     return Collections.unmodifiableSet(this.families.keySet());
969   }
970 
971   /** 
972    * Returns an array all the {@link HColumnDescriptor} of the column families 
973    * of the table.
974    *  
975    * @return Array of all the HColumnDescriptors of the current table 
976    * 
977    * @see #getFamilies()
978    */
979   public HColumnDescriptor[] getColumnFamilies() {
980     return getFamilies().toArray(new HColumnDescriptor[0]);
981   }
982   
983 
984   /**
985    * Returns the HColumnDescriptor for a specific column family with name as 
986    * specified by the parameter column.
987    * 
988    * @param column Column family name 
989    * @return Column descriptor for the passed family name or the family on
990    * passed in column.
991    */
992   public HColumnDescriptor getFamily(final byte [] column) {
993     return this.families.get(column);
994   }
995   
996 
997   /**
998    * Removes the HColumnDescriptor with name specified by the parameter column 
999    * from the table descriptor
1000    * 
1001    * @param column Name of the column family to be removed.
1002    * @return Column descriptor for the passed family name or the family on
1003    * passed in column.
1004    */
1005   public HColumnDescriptor removeFamily(final byte [] column) {
1006     return this.families.remove(column);
1007   }
1008   
1009 
1010   /**
1011    * Add a table coprocessor to this table. The coprocessor
1012    * type must be {@link org.apache.hadoop.hbase.coprocessor.RegionObserver}
1013    * or Endpoint.
1014    * It won't check if the class can be loaded or not.
1015    * Whether a coprocessor is loadable or not will be determined when
1016    * a region is opened.
1017    * @param className Full class name.
1018    * @throws IOException
1019    */
1020   public void addCoprocessor(String className) throws IOException {
1021     addCoprocessor(className, null, Coprocessor.PRIORITY_USER, null);
1022   }
1023 
1024   
1025   /**
1026    * Add a table coprocessor to this table. The coprocessor
1027    * type must be {@link org.apache.hadoop.hbase.coprocessor.RegionObserver}
1028    * or Endpoint.
1029    * It won't check if the class can be loaded or not.
1030    * Whether a coprocessor is loadable or not will be determined when
1031    * a region is opened.
1032    * @param jarFilePath Path of the jar file. If it's null, the class will be
1033    * loaded from default classloader.
1034    * @param className Full class name.
1035    * @param priority Priority
1036    * @param kvs Arbitrary key-value parameter pairs passed into the coprocessor.
1037    * @throws IOException
1038    */
1039   public void addCoprocessor(String className, Path jarFilePath,
1040                              int priority, final Map<String, String> kvs)
1041   throws IOException {
1042     if (hasCoprocessor(className)) {
1043       throw new IOException("Coprocessor " + className + " already exists.");
1044     }
1045     // validate parameter kvs
1046     StringBuilder kvString = new StringBuilder();
1047     if (kvs != null) {
1048       for (Map.Entry<String, String> e: kvs.entrySet()) {
1049         if (!e.getKey().matches(HConstants.CP_HTD_ATTR_VALUE_PARAM_KEY_PATTERN)) {
1050           throw new IOException("Illegal parameter key = " + e.getKey());
1051         }
1052         if (!e.getValue().matches(HConstants.CP_HTD_ATTR_VALUE_PARAM_VALUE_PATTERN)) {
1053           throw new IOException("Illegal parameter (" + e.getKey() +
1054               ") value = " + e.getValue());
1055         }
1056         if (kvString.length() != 0) {
1057           kvString.append(',');
1058         }
1059         kvString.append(e.getKey());
1060         kvString.append('=');
1061         kvString.append(e.getValue());
1062       }
1063     }
1064 
1065     // generate a coprocessor key
1066     int maxCoprocessorNumber = 0;
1067     Matcher keyMatcher;
1068     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1069         this.values.entrySet()) {
1070       keyMatcher =
1071           HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(
1072               Bytes.toString(e.getKey().get()));
1073       if (!keyMatcher.matches()) {
1074         continue;
1075       }
1076       maxCoprocessorNumber = Math.max(Integer.parseInt(keyMatcher.group(1)),
1077           maxCoprocessorNumber);
1078     }
1079     maxCoprocessorNumber++;
1080 
1081     String key = "coprocessor$" + Integer.toString(maxCoprocessorNumber);
1082     String value = ((jarFilePath == null)? "" : jarFilePath.toString()) +
1083         "|" + className + "|" + Integer.toString(priority) + "|" +
1084         kvString.toString();
1085     setValue(key, value);
1086   }
1087 
1088 
1089   /**
1090    * Check if the table has an attached co-processor represented by the name className
1091    *
1092    * @param className - Class name of the co-processor
1093    * @return true of the table has a co-processor className
1094    */
1095   public boolean hasCoprocessor(String className) {
1096     Matcher keyMatcher;
1097     Matcher valueMatcher;
1098     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1099         this.values.entrySet()) {
1100       keyMatcher =
1101           HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(
1102               Bytes.toString(e.getKey().get()));
1103       if (!keyMatcher.matches()) {
1104         continue;
1105       }
1106       valueMatcher =
1107         HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(
1108             Bytes.toString(e.getValue().get()));
1109       if (!valueMatcher.matches()) {
1110         continue;
1111       }
1112       // get className and compare
1113       String clazz = valueMatcher.group(2).trim(); // classname is the 2nd field
1114       if (clazz.equals(className.trim())) {
1115         return true;
1116       }
1117     }
1118     return false;
1119   }
1120 
1121   /**
1122    * Return the list of attached co-processor represented by their name className
1123    *
1124    * @return The list of co-processors classNames
1125    */
1126   public List<String> getCoprocessors() {
1127     List<String> result = new ArrayList<String>();
1128     Matcher keyMatcher;
1129     Matcher valueMatcher;
1130     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : this.values.entrySet()) {
1131       keyMatcher = HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e.getKey().get()));
1132       if (!keyMatcher.matches()) {
1133         continue;
1134       }
1135       valueMatcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(Bytes
1136           .toString(e.getValue().get()));
1137       if (!valueMatcher.matches()) {
1138         continue;
1139       }
1140       result.add(valueMatcher.group(2).trim()); // classname is the 2nd field
1141     }
1142     return result;
1143   }
1144 
1145   /**
1146    * Remove a coprocessor from those set on the table
1147    * @param className Class name of the co-processor
1148    */
1149   public void removeCoprocessor(String className) {
1150     ImmutableBytesWritable match = null;
1151     Matcher keyMatcher;
1152     Matcher valueMatcher;
1153     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e : this.values
1154         .entrySet()) {
1155       keyMatcher = HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(Bytes.toString(e
1156           .getKey().get()));
1157       if (!keyMatcher.matches()) {
1158         continue;
1159       }
1160       valueMatcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(Bytes
1161           .toString(e.getValue().get()));
1162       if (!valueMatcher.matches()) {
1163         continue;
1164       }
1165       // get className and compare
1166       String clazz = valueMatcher.group(2).trim(); // classname is the 2nd field
1167       // remove the CP if it is present
1168       if (clazz.equals(className.trim())) {
1169         match = e.getKey();
1170         break;
1171       }
1172     }
1173     // if we found a match, remove it
1174     if (match != null)
1175       this.values.remove(match);
1176   }
1177   
1178   /**
1179    * Returns the {@link Path} object representing the table directory under 
1180    * path rootdir 
1181    * 
1182    * @param rootdir qualified path of HBase root directory
1183    * @param tableName name of table
1184    * @return {@link Path} for table
1185    */
1186   public static Path getTableDir(Path rootdir, final byte [] tableName) {
1187     return new Path(rootdir, Bytes.toString(tableName));
1188   }
1189 
1190   /** Table descriptor for <core>-ROOT-</code> catalog table */
1191   public static final HTableDescriptor ROOT_TABLEDESC = new HTableDescriptor(
1192       HConstants.ROOT_TABLE_NAME,
1193       new HColumnDescriptor[] {
1194           new HColumnDescriptor(HConstants.CATALOG_FAMILY)
1195               // Ten is arbitrary number.  Keep versions to help debugging.
1196               .setMaxVersions(10)
1197               .setInMemory(true)
1198               .setBlocksize(8 * 1024)
1199               .setTimeToLive(HConstants.FOREVER)
1200               .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
1201       });
1202 
1203   /** Table descriptor for <code>.META.</code> catalog table */
1204   public static final HTableDescriptor META_TABLEDESC = new HTableDescriptor(
1205       HConstants.META_TABLE_NAME, new HColumnDescriptor[] {
1206           new HColumnDescriptor(HConstants.CATALOG_FAMILY)
1207               // Ten is arbitrary number.  Keep versions to help debugging.
1208               .setMaxVersions(10)
1209               .setInMemory(true)
1210               .setBlocksize(8 * 1024)
1211               .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
1212       });
1213 
1214   @Deprecated
1215   public void setOwner(User owner) {
1216     setOwnerString(owner != null ? owner.getShortName() : null);
1217   }
1218 
1219   // used by admin.rb:alter(table_name,*args) to update owner.
1220   @Deprecated
1221   public void setOwnerString(String ownerString) {
1222     if (ownerString != null) {
1223       setValue(OWNER_KEY, Bytes.toBytes(ownerString));
1224     } else {
1225       values.remove(OWNER_KEY);
1226     }
1227   }
1228 
1229   @Deprecated
1230   public String getOwnerString() {
1231     if (getValue(OWNER_KEY) != null) {
1232       return Bytes.toString(getValue(OWNER_KEY));
1233     }
1234     // Note that every table should have an owner (i.e. should have OWNER_KEY set).
1235     // .META. and -ROOT- should return system user as owner, not null (see
1236     // MasterFileSystem.java:bootstrap()).
1237     return null;
1238   }
1239 }