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.thrift2;
20  
21  import java.io.Closeable;
22  import java.io.IOException;
23  import java.util.Collection;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.hbase.HBaseConfiguration;
30  import org.apache.hadoop.hbase.HTableDescriptor;
31  import org.apache.hadoop.hbase.TableName;
32  import org.apache.hadoop.hbase.client.*;
33  import org.apache.hadoop.hbase.client.coprocessor.Batch;
34  import org.apache.hadoop.hbase.client.coprocessor.Batch.Callback;
35  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
36  import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
37  import org.apache.hadoop.hbase.util.Bytes;
38  import org.apache.hadoop.hbase.util.PoolMap;
39  import org.apache.hadoop.hbase.util.PoolMap.PoolType;
40  
41  import com.google.protobuf.Descriptors;
42  import com.google.protobuf.Message;
43  import com.google.protobuf.Service;
44  import com.google.protobuf.ServiceException;
45  
46  /**
47   * A simple pool of HTable instances.
48   *
49   * Each HTablePool acts as a pool for all tables. To use, instantiate an
50   * HTablePool and use {@link #getTable(String)} to get an HTable from the pool.
51   *
52   * This method is not needed anymore, clients should call
53   * HTableInterface.close() rather than returning the tables to the pool
54   *
55   * Once you are done with it, close your instance of
56   * {@link org.apache.hadoop.hbase.client.HTableInterface}
57   * by calling {@link org.apache.hadoop.hbase.client.HTableInterface#close()} rather than returning
58   * the tablesto the pool with (deprecated)
59   * {@link #putTable(org.apache.hadoop.hbase.client.HTableInterface)}.
60   *
61   * <p>
62   * A pool can be created with a <i>maxSize</i> which defines the most HTable
63   * references that will ever be retained for each table. Otherwise the default
64   * is {@link Integer#MAX_VALUE}.
65   *
66   * <p>
67   * Pool will manage its own connections to the cluster. See
68   * {@link org.apache.hadoop.hbase.client.HConnectionManager}.
69   * Was @deprecated made @InterfaceAudience.private as of 0.98.1.
70   * See {@link org.apache.hadoop.hbase.client.HConnection#getTable(String)},
71   * Moved to thrift2 module for 2.0
72   */
73  @InterfaceAudience.Private
74  public class HTablePool implements Closeable {
75    private final PoolMap<String, HTableInterface> tables;
76    private final int maxSize;
77    private final PoolType poolType;
78    private final Configuration config;
79    private final HTableInterfaceFactory tableFactory;
80  
81    /**
82     * Default Constructor. Default HBaseConfiguration and no limit on pool size.
83     */
84    public HTablePool() {
85      this(HBaseConfiguration.create(), Integer.MAX_VALUE);
86    }
87  
88    /**
89     * Constructor to set maximum versions and use the specified configuration.
90     *
91     * @param config
92     *          configuration
93     * @param maxSize
94     *          maximum number of references to keep for each table
95     */
96    public HTablePool(final Configuration config, final int maxSize) {
97      this(config, maxSize, null, null);
98    }
99  
100   /**
101    * Constructor to set maximum versions and use the specified configuration and
102    * table factory.
103    *
104    * @param config
105    *          configuration
106    * @param maxSize
107    *          maximum number of references to keep for each table
108    * @param tableFactory
109    *          table factory
110    */
111   public HTablePool(final Configuration config, final int maxSize,
112       final HTableInterfaceFactory tableFactory) {
113     this(config, maxSize, tableFactory, PoolType.Reusable);
114   }
115 
116   /**
117    * Constructor to set maximum versions and use the specified configuration and
118    * pool type.
119    *
120    * @param config
121    *          configuration
122    * @param maxSize
123    *          maximum number of references to keep for each table
124    * @param poolType
125    *          pool type which is one of {@link PoolType#Reusable} or
126    *          {@link PoolType#ThreadLocal}
127    */
128   public HTablePool(final Configuration config, final int maxSize,
129       final PoolType poolType) {
130     this(config, maxSize, null, poolType);
131   }
132 
133   /**
134    * Constructor to set maximum versions and use the specified configuration,
135    * table factory and pool type. The HTablePool supports the
136    * {@link PoolType#Reusable} and {@link PoolType#ThreadLocal}. If the pool
137    * type is null or not one of those two values, then it will default to
138    * {@link PoolType#Reusable}.
139    *
140    * @param config
141    *          configuration
142    * @param maxSize
143    *          maximum number of references to keep for each table
144    * @param tableFactory
145    *          table factory
146    * @param poolType
147    *          pool type which is one of {@link PoolType#Reusable} or
148    *          {@link PoolType#ThreadLocal}
149    */
150   public HTablePool(final Configuration config, final int maxSize,
151       final HTableInterfaceFactory tableFactory, PoolType poolType) {
152     // Make a new configuration instance so I can safely cleanup when
153     // done with the pool.
154     this.config = config == null ? HBaseConfiguration.create() : config;
155     this.maxSize = maxSize;
156     this.tableFactory = tableFactory == null ? new HTableFactory()
157         : tableFactory;
158     if (poolType == null) {
159       this.poolType = PoolType.Reusable;
160     } else {
161       switch (poolType) {
162       case Reusable:
163       case ThreadLocal:
164         this.poolType = poolType;
165         break;
166       default:
167         this.poolType = PoolType.Reusable;
168         break;
169       }
170     }
171     this.tables = new PoolMap<String, HTableInterface>(this.poolType,
172         this.maxSize);
173   }
174 
175   /**
176    * Get a reference to the specified table from the pool.
177    * <p>
178    * <p/>
179    *
180    * @param tableName
181    *          table name
182    * @return a reference to the specified table
183    * @throws RuntimeException
184    *           if there is a problem instantiating the HTable
185    */
186   public HTableInterface getTable(String tableName) {
187     // call the old getTable implementation renamed to findOrCreateTable
188     HTableInterface table = findOrCreateTable(tableName);
189     // return a proxy table so when user closes the proxy, the actual table
190     // will be returned to the pool
191     return new PooledHTable(table);
192   }
193 
194   /**
195    * Get a reference to the specified table from the pool.
196    * <p>
197    *
198    * Create a new one if one is not available.
199    *
200    * @param tableName
201    *          table name
202    * @return a reference to the specified table
203    * @throws RuntimeException
204    *           if there is a problem instantiating the HTable
205    */
206   private HTableInterface findOrCreateTable(String tableName) {
207     HTableInterface table = tables.get(tableName);
208     if (table == null) {
209       table = createHTable(tableName);
210     }
211     return table;
212   }
213 
214   /**
215    * Get a reference to the specified table from the pool.
216    * <p>
217    *
218    * Create a new one if one is not available.
219    *
220    * @param tableName
221    *          table name
222    * @return a reference to the specified table
223    * @throws RuntimeException
224    *           if there is a problem instantiating the HTable
225    */
226   public HTableInterface getTable(byte[] tableName) {
227     return getTable(Bytes.toString(tableName));
228   }
229 
230   /**
231    * This method is not needed anymore, clients should call
232    * HTableInterface.close() rather than returning the tables to the pool
233    *
234    * @param table
235    *          the proxy table user got from pool
236    * @deprecated
237    */
238   public void putTable(HTableInterface table) throws IOException {
239     // we need to be sure nobody puts a proxy implementation in the pool
240     // but if the client code is not updated
241     // and it will continue to call putTable() instead of calling close()
242     // then we need to return the wrapped table to the pool instead of the
243     // proxy
244     // table
245     if (table instanceof PooledHTable) {
246       returnTable(((PooledHTable) table).getWrappedTable());
247     } else {
248       // normally this should not happen if clients pass back the same
249       // table
250       // object they got from the pool
251       // but if it happens then it's better to reject it
252       throw new IllegalArgumentException("not a pooled table: " + table);
253     }
254   }
255 
256   /**
257    * Puts the specified HTable back into the pool.
258    * <p>
259    *
260    * If the pool already contains <i>maxSize</i> references to the table, then
261    * the table instance gets closed after flushing buffered edits.
262    *
263    * @param table
264    *          table
265    */
266   private void returnTable(HTableInterface table) throws IOException {
267     // this is the old putTable method renamed and made private
268     String tableName = Bytes.toString(table.getTableName());
269     if (tables.size(tableName) >= maxSize) {
270       // release table instance since we're not reusing it
271       this.tables.removeValue(tableName, table);
272       this.tableFactory.releaseHTableInterface(table);
273       return;
274     }
275     tables.put(tableName, table);
276   }
277 
278   protected HTableInterface createHTable(String tableName) {
279     return this.tableFactory.createHTableInterface(config,
280         Bytes.toBytes(tableName));
281   }
282 
283   /**
284    * Closes all the HTable instances , belonging to the given table, in the
285    * table pool.
286    * <p>
287    * Note: this is a 'shutdown' of the given table pool and different from
288    * {@link #putTable(HTableInterface)}, that is used to return the table
289    * instance to the pool for future re-use.
290    *
291    * @param tableName
292    */
293   public void closeTablePool(final String tableName) throws IOException {
294     Collection<HTableInterface> tables = this.tables.values(tableName);
295     if (tables != null) {
296       for (HTableInterface table : tables) {
297         this.tableFactory.releaseHTableInterface(table);
298       }
299     }
300     this.tables.remove(tableName);
301   }
302 
303   /**
304    * See {@link #closeTablePool(String)}.
305    *
306    * @param tableName
307    */
308   public void closeTablePool(final byte[] tableName) throws IOException {
309     closeTablePool(Bytes.toString(tableName));
310   }
311 
312   /**
313    * Closes all the HTable instances , belonging to all tables in the table
314    * pool.
315    * <p>
316    * Note: this is a 'shutdown' of all the table pools.
317    */
318   public void close() throws IOException {
319     for (String tableName : tables.keySet()) {
320       closeTablePool(tableName);
321     }
322     this.tables.clear();
323   }
324 
325   public int getCurrentPoolSize(String tableName) {
326     return tables.size(tableName);
327   }
328 
329   /**
330    * A proxy class that implements HTableInterface.close method to return the
331    * wrapped table back to the table pool
332    *
333    */
334   class PooledHTable implements HTableInterface {
335 
336     private boolean open = false;
337 
338     private HTableInterface table; // actual table implementation
339 
340     public PooledHTable(HTableInterface table) {
341       this.table = table;
342       this.open = true;
343     }
344 
345     @Override
346     public byte[] getTableName() {
347       checkState();
348       return table.getTableName();
349     }
350 
351     @Override
352     public TableName getName() {
353       return table.getName();
354     }
355 
356     @Override
357     public Configuration getConfiguration() {
358       checkState();
359       return table.getConfiguration();
360     }
361 
362     @Override
363     public HTableDescriptor getTableDescriptor() throws IOException {
364       checkState();
365       return table.getTableDescriptor();
366     }
367 
368     @Override
369     public boolean exists(Get get) throws IOException {
370       checkState();
371       return table.exists(get);
372     }
373 
374     @Override
375     public boolean[] existsAll(List<Get> gets) throws IOException {
376       checkState();
377       return table.existsAll(gets);
378     }
379 
380     @Override
381     public Boolean[] exists(List<Get> gets) throws IOException {
382       checkState();
383       return table.exists(gets);
384     }
385 
386     @Override
387     public void batch(List<? extends Row> actions, Object[] results) throws IOException,
388         InterruptedException {
389       checkState();
390       table.batch(actions, results);
391     }
392 
393     /**
394      * {@inheritDoc}
395      * @deprecated If any exception is thrown by one of the actions, there is no way to
396      * retrieve the partially executed results. Use {@link #batch(List, Object[])} instead.
397      */
398     @Override
399     public Object[] batch(List<? extends Row> actions) throws IOException,
400         InterruptedException {
401       checkState();
402       return table.batch(actions);
403     }
404 
405     @Override
406     public Result get(Get get) throws IOException {
407       checkState();
408       return table.get(get);
409     }
410 
411     @Override
412     public Result[] get(List<Get> gets) throws IOException {
413       checkState();
414       return table.get(gets);
415     }
416 
417     @Override
418     @SuppressWarnings("deprecation")
419     @Deprecated
420     public Result getRowOrBefore(byte[] row, byte[] family) throws IOException {
421       checkState();
422       return table.getRowOrBefore(row, family);
423     }
424 
425     @Override
426     public ResultScanner getScanner(Scan scan) throws IOException {
427       checkState();
428       return table.getScanner(scan);
429     }
430 
431     @Override
432     public ResultScanner getScanner(byte[] family) throws IOException {
433       checkState();
434       return table.getScanner(family);
435     }
436 
437     @Override
438     public ResultScanner getScanner(byte[] family, byte[] qualifier)
439         throws IOException {
440       checkState();
441       return table.getScanner(family, qualifier);
442     }
443 
444     @Override
445     public void put(Put put) throws IOException {
446       checkState();
447       table.put(put);
448     }
449 
450     @Override
451     public void put(List<Put> puts) throws IOException {
452       checkState();
453       table.put(puts);
454     }
455 
456     @Override
457     public boolean checkAndPut(byte[] row, byte[] family, byte[] qualifier,
458         byte[] value, Put put) throws IOException {
459       checkState();
460       return table.checkAndPut(row, family, qualifier, value, put);
461     }
462 
463     @Override
464     public boolean checkAndPut(byte[] row, byte[] family, byte[] qualifier,
465         CompareOp compareOp, byte[] value, Put put) throws IOException {
466       checkState();
467       return table.checkAndPut(row, family, qualifier, compareOp, value, put);
468     }
469 
470     @Override
471     public void delete(Delete delete) throws IOException {
472       checkState();
473       table.delete(delete);
474     }
475 
476     @Override
477     public void delete(List<Delete> deletes) throws IOException {
478       checkState();
479       table.delete(deletes);
480     }
481 
482     @Override
483     public boolean checkAndDelete(byte[] row, byte[] family, byte[] qualifier,
484         byte[] value, Delete delete) throws IOException {
485       checkState();
486       return table.checkAndDelete(row, family, qualifier, value, delete);
487     }
488 
489     @Override
490     public boolean checkAndDelete(byte[] row, byte[] family, byte[] qualifier,
491         CompareOp compareOp, byte[] value, Delete delete) throws IOException {
492       checkState();
493       return table.checkAndDelete(row, family, qualifier, compareOp, value, delete);
494     }
495 
496     @Override
497     public Result increment(Increment increment) throws IOException {
498       checkState();
499       return table.increment(increment);
500     }
501 
502     @Override
503     public long incrementColumnValue(byte[] row, byte[] family,
504         byte[] qualifier, long amount) throws IOException {
505       checkState();
506       return table.incrementColumnValue(row, family, qualifier, amount);
507     }
508 
509     @Override
510     public long incrementColumnValue(byte[] row, byte[] family,
511         byte[] qualifier, long amount, Durability durability) throws IOException {
512       checkState();
513       return table.incrementColumnValue(row, family, qualifier, amount,
514           durability);
515     }
516 
517     @Override
518     public boolean isAutoFlush() {
519       checkState();
520       return table.isAutoFlush();
521     }
522 
523     @Override
524     public void flushCommits() throws IOException {
525       checkState();
526       table.flushCommits();
527     }
528 
529     /**
530      * Returns the actual table back to the pool
531      *
532      * @throws IOException
533      */
534     public void close() throws IOException {
535       checkState();
536       open = false;
537       returnTable(table);
538     }
539 
540     @Override
541     public CoprocessorRpcChannel coprocessorService(byte[] row) {
542       checkState();
543       return table.coprocessorService(row);
544     }
545 
546     @Override
547     public <T extends Service, R> Map<byte[], R> coprocessorService(Class<T> service,
548         byte[] startKey, byte[] endKey, Batch.Call<T, R> callable)
549         throws ServiceException, Throwable {
550       checkState();
551       return table.coprocessorService(service, startKey, endKey, callable);
552     }
553 
554     @Override
555     public <T extends Service, R> void coprocessorService(Class<T> service,
556         byte[] startKey, byte[] endKey, Batch.Call<T, R> callable, Callback<R> callback)
557         throws ServiceException, Throwable {
558       checkState();
559       table.coprocessorService(service, startKey, endKey, callable, callback);
560     }
561 
562     @Override
563     public String toString() {
564       return "PooledHTable{" + ", table=" + table + '}';
565     }
566 
567     /**
568      * Expose the wrapped HTable to tests in the same package
569      *
570      * @return wrapped htable
571      */
572     HTableInterface getWrappedTable() {
573       return table;
574     }
575 
576     @Override
577     public <R> void batchCallback(List<? extends Row> actions,
578         Object[] results, Callback<R> callback) throws IOException,
579         InterruptedException {
580       checkState();
581       table.batchCallback(actions, results, callback);
582     }
583 
584     /**
585      * {@inheritDoc}
586      * @deprecated If any exception is thrown by one of the actions, there is no way to
587      * retrieve the partially executed results. Use
588      * {@link #batchCallback(List, Object[], org.apache.hadoop.hbase.client.coprocessor.Batch.Callback)}
589      * instead.
590      */
591     @Override
592     public <R> Object[] batchCallback(List<? extends Row> actions,
593         Callback<R> callback) throws IOException, InterruptedException {
594       checkState();
595       return table.batchCallback(actions,  callback);
596     }
597 
598     @Override
599     public void mutateRow(RowMutations rm) throws IOException {
600       checkState();
601       table.mutateRow(rm);
602     }
603 
604     @Override
605     public Result append(Append append) throws IOException {
606       checkState();
607       return table.append(append);
608     }
609 
610     @Override
611     public void setAutoFlush(boolean autoFlush) {
612       checkState();
613       table.setAutoFlush(autoFlush, autoFlush);
614     }
615 
616     @Override
617     public void setAutoFlush(boolean autoFlush, boolean clearBufferOnFail) {
618       checkState();
619       table.setAutoFlush(autoFlush, clearBufferOnFail);
620     }
621 
622     @Override
623     public void setAutoFlushTo(boolean autoFlush) {
624       table.setAutoFlushTo(autoFlush);
625     }
626 
627     @Override
628     public long getWriteBufferSize() {
629       checkState();
630       return table.getWriteBufferSize();
631     }
632 
633     @Override
634     public void setWriteBufferSize(long writeBufferSize) throws IOException {
635       checkState();
636       table.setWriteBufferSize(writeBufferSize);
637     }
638 
639     boolean isOpen() {
640       return open;
641     }
642 
643     private void checkState() {
644       if (!isOpen()) {
645         throw new IllegalStateException("Table=" + new String(table.getTableName())
646                 + " already closed");
647       }
648     }
649 
650     @Override
651     public long incrementColumnValue(byte[] row, byte[] family,
652         byte[] qualifier, long amount, boolean writeToWAL) throws IOException {
653       return table.incrementColumnValue(row, family, qualifier, amount, writeToWAL);
654     }
655 
656     @Override
657     public <R extends Message> Map<byte[], R> batchCoprocessorService(
658         Descriptors.MethodDescriptor method, Message request,
659         byte[] startKey, byte[] endKey, R responsePrototype) throws ServiceException, Throwable {
660       checkState();
661       return table.batchCoprocessorService(method, request, startKey, endKey,
662           responsePrototype);
663     }
664 
665     @Override
666     public <R extends Message> void batchCoprocessorService(
667         Descriptors.MethodDescriptor method, Message request,
668         byte[] startKey, byte[] endKey, R responsePrototype, Callback<R> callback)
669         throws ServiceException, Throwable {
670       checkState();
671       table.batchCoprocessorService(method, request, startKey, endKey, responsePrototype, callback);
672     }
673 
674     @Override
675     public boolean checkAndMutate(byte[] row, byte[] family, byte[] qualifier, CompareOp compareOp,
676         byte[] value, RowMutations mutation) throws IOException {
677       checkState();
678       return table.checkAndMutate(row, family, qualifier, compareOp, value, mutation);
679     }
680   }
681 }