View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.thrift;
20  
21  import static org.apache.hadoop.hbase.util.Bytes.getBytes;
22  
23  import java.io.IOException;
24  import java.net.InetAddress;
25  import java.net.InetSocketAddress;
26  import java.net.UnknownHostException;
27  import java.nio.ByteBuffer;
28  import java.security.PrivilegedAction;
29  import java.util.ArrayList;
30  import java.util.Arrays;
31  import java.util.Collections;
32  import java.util.HashMap;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.TreeMap;
36  import java.util.concurrent.BlockingQueue;
37  import java.util.concurrent.ExecutorService;
38  import java.util.concurrent.LinkedBlockingQueue;
39  import java.util.concurrent.ThreadPoolExecutor;
40  import java.util.concurrent.TimeUnit;
41  
42  import javax.security.auth.callback.Callback;
43  import javax.security.auth.callback.UnsupportedCallbackException;
44  import javax.security.sasl.AuthorizeCallback;
45  import javax.security.sasl.Sasl;
46  import javax.security.sasl.SaslServer;
47  
48  import org.apache.commons.cli.CommandLine;
49  import org.apache.commons.cli.Option;
50  import org.apache.commons.cli.OptionGroup;
51  import org.apache.commons.logging.Log;
52  import org.apache.commons.logging.LogFactory;
53  import org.apache.hadoop.conf.Configuration;
54  import org.apache.hadoop.hbase.HBaseConfiguration;
55  import org.apache.hadoop.hbase.HColumnDescriptor;
56  import org.apache.hadoop.hbase.HConstants;
57  import org.apache.hadoop.hbase.HRegionInfo;
58  import org.apache.hadoop.hbase.HRegionLocation;
59  import org.apache.hadoop.hbase.HTableDescriptor;
60  import org.apache.hadoop.hbase.KeyValue;
61  import org.apache.hadoop.hbase.MetaTableAccessor;
62  import org.apache.hadoop.hbase.ServerName;
63  import org.apache.hadoop.hbase.TableName;
64  import org.apache.hadoop.hbase.TableNotFoundException;
65  import org.apache.hadoop.hbase.classification.InterfaceAudience;
66  import org.apache.hadoop.hbase.client.Admin;
67  import org.apache.hadoop.hbase.client.Append;
68  import org.apache.hadoop.hbase.client.Delete;
69  import org.apache.hadoop.hbase.client.Durability;
70  import org.apache.hadoop.hbase.client.Get;
71  import org.apache.hadoop.hbase.client.Increment;
72  import org.apache.hadoop.hbase.client.OperationWithAttributes;
73  import org.apache.hadoop.hbase.client.Put;
74  import org.apache.hadoop.hbase.client.RegionLocator;
75  import org.apache.hadoop.hbase.client.Result;
76  import org.apache.hadoop.hbase.client.ResultScanner;
77  import org.apache.hadoop.hbase.client.Scan;
78  import org.apache.hadoop.hbase.client.Table;
79  import org.apache.hadoop.hbase.filter.Filter;
80  import org.apache.hadoop.hbase.filter.ParseFilter;
81  import org.apache.hadoop.hbase.filter.PrefixFilter;
82  import org.apache.hadoop.hbase.filter.WhileMatchFilter;
83  import org.apache.hadoop.hbase.security.SecurityUtil;
84  import org.apache.hadoop.hbase.security.UserProvider;
85  import org.apache.hadoop.hbase.thrift.CallQueue.Call;
86  import org.apache.hadoop.hbase.thrift.generated.AlreadyExists;
87  import org.apache.hadoop.hbase.thrift.generated.BatchMutation;
88  import org.apache.hadoop.hbase.thrift.generated.ColumnDescriptor;
89  import org.apache.hadoop.hbase.thrift.generated.Hbase;
90  import org.apache.hadoop.hbase.thrift.generated.IOError;
91  import org.apache.hadoop.hbase.thrift.generated.IllegalArgument;
92  import org.apache.hadoop.hbase.thrift.generated.Mutation;
93  import org.apache.hadoop.hbase.thrift.generated.TAppend;
94  import org.apache.hadoop.hbase.thrift.generated.TCell;
95  import org.apache.hadoop.hbase.thrift.generated.TIncrement;
96  import org.apache.hadoop.hbase.thrift.generated.TRegionInfo;
97  import org.apache.hadoop.hbase.thrift.generated.TRowResult;
98  import org.apache.hadoop.hbase.thrift.generated.TScan;
99  import org.apache.hadoop.hbase.util.Bytes;
100 import org.apache.hadoop.hbase.util.ConnectionCache;
101 import org.apache.hadoop.hbase.util.DNS;
102 import org.apache.hadoop.hbase.util.Strings;
103 import org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler;
104 import org.apache.hadoop.security.UserGroupInformation;
105 import org.apache.hadoop.security.authorize.ProxyUsers;
106 import org.apache.thrift.TException;
107 import org.apache.thrift.TProcessor;
108 import org.apache.thrift.protocol.TBinaryProtocol;
109 import org.apache.thrift.protocol.TCompactProtocol;
110 import org.apache.thrift.protocol.TProtocol;
111 import org.apache.thrift.protocol.TProtocolFactory;
112 import org.apache.thrift.server.THsHaServer;
113 import org.apache.thrift.server.TNonblockingServer;
114 import org.apache.thrift.server.TServer;
115 import org.apache.thrift.server.TServlet;
116 import org.apache.thrift.server.TThreadedSelectorServer;
117 import org.apache.thrift.transport.TFramedTransport;
118 import org.apache.thrift.transport.TNonblockingServerSocket;
119 import org.apache.thrift.transport.TNonblockingServerTransport;
120 import org.apache.thrift.transport.TSaslServerTransport;
121 import org.apache.thrift.transport.TServerSocket;
122 import org.apache.thrift.transport.TServerTransport;
123 import org.apache.thrift.transport.TTransportFactory;
124 import org.mortbay.jetty.Connector;
125 import org.mortbay.jetty.Server;
126 import org.mortbay.jetty.nio.SelectChannelConnector;
127 import org.mortbay.jetty.security.SslSelectChannelConnector;
128 import org.mortbay.jetty.servlet.Context;
129 import org.mortbay.jetty.servlet.ServletHolder;
130 import org.mortbay.thread.QueuedThreadPool;
131 
132 import com.google.common.base.Joiner;
133 import com.google.common.base.Throwables;
134 import com.google.common.util.concurrent.ThreadFactoryBuilder;
135 
136 /**
137  * ThriftServerRunner - this class starts up a Thrift server which implements
138  * the Hbase API specified in the Hbase.thrift IDL file.
139  */
140 @InterfaceAudience.Private
141 public class ThriftServerRunner implements Runnable {
142 
143   private static final Log LOG = LogFactory.getLog(ThriftServerRunner.class);
144 
145   static final String SERVER_TYPE_CONF_KEY =
146       "hbase.regionserver.thrift.server.type";
147 
148   static final String BIND_CONF_KEY = "hbase.regionserver.thrift.ipaddress";
149   static final String COMPACT_CONF_KEY = "hbase.regionserver.thrift.compact";
150   static final String FRAMED_CONF_KEY = "hbase.regionserver.thrift.framed";
151   static final String MAX_FRAME_SIZE_CONF_KEY = "hbase.regionserver.thrift.framed.max_frame_size_in_mb";
152   static final String PORT_CONF_KEY = "hbase.regionserver.thrift.port";
153   static final String COALESCE_INC_KEY = "hbase.regionserver.thrift.coalesceIncrement";
154   static final String USE_HTTP_CONF_KEY = "hbase.regionserver.thrift.http";
155   static final String HTTP_MIN_THREADS = "hbase.thrift.http_threads.min";
156   static final String HTTP_MAX_THREADS = "hbase.thrift.http_threads.max";
157 
158   static final String THRIFT_SSL_ENABLED = "hbase.thrift.ssl.enabled";
159   static final String THRIFT_SSL_KEYSTORE_STORE = "hbase.thrift.ssl.keystore.store";
160   static final String THRIFT_SSL_KEYSTORE_PASSWORD = "hbase.thrift.ssl.keystore.password";
161   static final String THRIFT_SSL_KEYSTORE_KEYPASSWORD = "hbase.thrift.ssl.keystore.keypassword";
162 
163   /**
164    * Amount of time in milliseconds before a server thread will timeout
165    * waiting for client to send data on a connected socket. Currently,
166    * applies only to TBoundedThreadPoolServer
167    */
168   public static final String THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY =
169     "hbase.thrift.server.socket.read.timeout";
170   public static final int THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT = 60000;
171 
172 
173   /**
174    * Thrift quality of protection configuration key. Valid values can be:
175    * auth-conf: authentication, integrity and confidentiality checking
176    * auth-int: authentication and integrity checking
177    * auth: authentication only
178    *
179    * This is used to authenticate the callers and support impersonation.
180    * The thrift server and the HBase cluster must run in secure mode.
181    */
182   static final String THRIFT_QOP_KEY = "hbase.thrift.security.qop";
183   static final String BACKLOG_CONF_KEY = "hbase.regionserver.thrift.backlog";
184 
185   private static final String DEFAULT_BIND_ADDR = "0.0.0.0";
186   public static final int DEFAULT_LISTEN_PORT = 9090;
187   public static final int HREGION_VERSION = 1;
188   static final String THRIFT_SUPPORT_PROXYUSER = "hbase.thrift.support.proxyuser";
189   private final int listenPort;
190 
191   private Configuration conf;
192   volatile TServer tserver;
193   volatile Server httpServer;
194   private final Hbase.Iface handler;
195   private final ThriftMetrics metrics;
196   private final HBaseHandler hbaseHandler;
197   private final UserGroupInformation realUser;
198 
199   private final String qop;
200   private String host;
201 
202   private final boolean securityEnabled;
203   private final boolean doAsEnabled;
204 
205   /** An enum of server implementation selections */
206   enum ImplType {
207     HS_HA("hsha", true, THsHaServer.class, true),
208     NONBLOCKING("nonblocking", true, TNonblockingServer.class, true),
209     THREAD_POOL("threadpool", false, TBoundedThreadPoolServer.class, true),
210     THREADED_SELECTOR(
211         "threadedselector", true, TThreadedSelectorServer.class, true);
212 
213     public static final ImplType DEFAULT = THREAD_POOL;
214 
215     final String option;
216     final boolean isAlwaysFramed;
217     final Class<? extends TServer> serverClass;
218     final boolean canSpecifyBindIP;
219 
220     ImplType(String option, boolean isAlwaysFramed,
221         Class<? extends TServer> serverClass, boolean canSpecifyBindIP) {
222       this.option = option;
223       this.isAlwaysFramed = isAlwaysFramed;
224       this.serverClass = serverClass;
225       this.canSpecifyBindIP = canSpecifyBindIP;
226     }
227 
228     /**
229      * @return <code>-option</code> so we can get the list of options from
230      *         {@link #values()}
231      */
232     @Override
233     public String toString() {
234       return "-" + option;
235     }
236 
237     String getDescription() {
238       StringBuilder sb = new StringBuilder("Use the " +
239           serverClass.getSimpleName());
240       if (isAlwaysFramed) {
241         sb.append(" This implies the framed transport.");
242       }
243       if (this == DEFAULT) {
244         sb.append("This is the default.");
245       }
246       return sb.toString();
247     }
248 
249     static OptionGroup createOptionGroup() {
250       OptionGroup group = new OptionGroup();
251       for (ImplType t : values()) {
252         group.addOption(new Option(t.option, t.getDescription()));
253       }
254       return group;
255     }
256 
257     static ImplType getServerImpl(Configuration conf) {
258       String confType = conf.get(SERVER_TYPE_CONF_KEY, THREAD_POOL.option);
259       for (ImplType t : values()) {
260         if (confType.equals(t.option)) {
261           return t;
262         }
263       }
264       throw new AssertionError("Unknown server ImplType.option:" + confType);
265     }
266 
267     static void setServerImpl(CommandLine cmd, Configuration conf) {
268       ImplType chosenType = null;
269       int numChosen = 0;
270       for (ImplType t : values()) {
271         if (cmd.hasOption(t.option)) {
272           chosenType = t;
273           ++numChosen;
274         }
275       }
276       if (numChosen < 1) {
277         LOG.info("Using default thrift server type");
278         chosenType = DEFAULT;
279       } else if (numChosen > 1) {
280         throw new AssertionError("Exactly one option out of " +
281           Arrays.toString(values()) + " has to be specified");
282       }
283       LOG.info("Using thrift server type " + chosenType.option);
284       conf.set(SERVER_TYPE_CONF_KEY, chosenType.option);
285     }
286 
287     public String simpleClassName() {
288       return serverClass.getSimpleName();
289     }
290 
291     public static List<String> serversThatCannotSpecifyBindIP() {
292       List<String> l = new ArrayList<String>();
293       for (ImplType t : values()) {
294         if (!t.canSpecifyBindIP) {
295           l.add(t.simpleClassName());
296         }
297       }
298       return l;
299     }
300 
301   }
302 
303   public ThriftServerRunner(Configuration conf) throws IOException {
304     UserProvider userProvider = UserProvider.instantiate(conf);
305     // login the server principal (if using secure Hadoop)
306     securityEnabled = userProvider.isHadoopSecurityEnabled()
307       && userProvider.isHBaseSecurityEnabled();
308     if (securityEnabled) {
309       host = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
310         conf.get("hbase.thrift.dns.interface", "default"),
311         conf.get("hbase.thrift.dns.nameserver", "default")));
312       userProvider.login("hbase.thrift.keytab.file",
313         "hbase.thrift.kerberos.principal", host);
314     }
315     this.conf = HBaseConfiguration.create(conf);
316     this.listenPort = conf.getInt(PORT_CONF_KEY, DEFAULT_LISTEN_PORT);
317     this.metrics = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.ONE);
318     this.hbaseHandler = new HBaseHandler(conf, userProvider);
319     this.hbaseHandler.initMetrics(metrics);
320     this.handler = HbaseHandlerMetricsProxy.newInstance(
321       hbaseHandler, metrics, conf);
322     this.realUser = userProvider.getCurrent().getUGI();
323     qop = conf.get(THRIFT_QOP_KEY);
324     doAsEnabled = conf.getBoolean(THRIFT_SUPPORT_PROXYUSER, false);
325     if (qop != null) {
326       if (!qop.equals("auth") && !qop.equals("auth-int")
327           && !qop.equals("auth-conf")) {
328         throw new IOException("Invalid " + THRIFT_QOP_KEY + ": " + qop
329           + ", it must be 'auth', 'auth-int', or 'auth-conf'");
330       }
331       if (!securityEnabled) {
332         throw new IOException("Thrift server must"
333           + " run in secure mode to support authentication");
334       }
335     }
336   }
337 
338   /*
339    * Runs the Thrift server
340    */
341   @Override
342   public void run() {
343     realUser.doAs(new PrivilegedAction<Object>() {
344       @Override
345       public Object run() {
346         try {
347           if (conf.getBoolean(USE_HTTP_CONF_KEY, false)) {
348             setupHTTPServer();
349             httpServer.start();
350             httpServer.join();
351           } else {
352             setupServer();
353             tserver.serve();
354           }
355         } catch (Exception e) {
356           LOG.fatal("Cannot run ThriftServer", e);
357           // Crash the process if the ThriftServer is not running
358           System.exit(-1);
359         }
360         return null;
361       }
362     });
363 
364   }
365 
366   public void shutdown() {
367     if (tserver != null) {
368       tserver.stop();
369       tserver = null;
370     }
371     if (httpServer != null) {
372       try {
373         httpServer.stop();
374         httpServer = null;
375       } catch (Exception e) {
376         LOG.error("Problem encountered in shutting down HTTP server " + e.getCause());
377       }
378       httpServer = null;
379     }
380   }
381 
382   private void setupHTTPServer() throws IOException {
383     TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
384     TProcessor processor = new Hbase.Processor<Hbase.Iface>(handler);
385     TServlet thriftHttpServlet = new ThriftHttpServlet(processor, protocolFactory, realUser,
386         conf, hbaseHandler, securityEnabled, doAsEnabled);
387 
388     httpServer = new Server();
389     // Context handler
390     Context context = new Context(httpServer, "/", Context.SESSIONS);
391     context.setContextPath("/");
392     String httpPath = "/*";
393     httpServer.setHandler(context);
394     context.addServlet(new ServletHolder(thriftHttpServlet), httpPath);
395 
396     // set up Jetty and run the embedded server
397     Connector connector = new SelectChannelConnector();
398     if(conf.getBoolean(THRIFT_SSL_ENABLED, false)) {
399       SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
400       String keystore = conf.get(THRIFT_SSL_KEYSTORE_STORE);
401       String password = HBaseConfiguration.getPassword(conf,
402           THRIFT_SSL_KEYSTORE_PASSWORD, null);
403       String keyPassword = HBaseConfiguration.getPassword(conf,
404           THRIFT_SSL_KEYSTORE_KEYPASSWORD, password);
405       sslConnector.setKeystore(keystore);
406       sslConnector.setPassword(password);
407       sslConnector.setKeyPassword(keyPassword);
408       connector = sslConnector;
409     }
410     String host = getBindAddress(conf).getHostAddress();
411     connector.setPort(listenPort);
412     connector.setHost(host);
413     connector.setHeaderBufferSize(1024 * 64);
414     httpServer.addConnector(connector);
415 
416     if (doAsEnabled) {
417       ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
418     }
419 
420     // Set the default max thread number to 100 to limit
421     // the number of concurrent requests so that Thrfit HTTP server doesn't OOM easily.
422     // Jetty set the default max thread number to 250, if we don't set it.
423     //
424     // Our default min thread number 2 is the same as that used by Jetty.
425     int minThreads = conf.getInt(HTTP_MIN_THREADS, 2);
426     int maxThreads = conf.getInt(HTTP_MAX_THREADS, 100);
427     QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads);
428     threadPool.setMinThreads(minThreads);
429     httpServer.setThreadPool(threadPool);
430 
431     httpServer.setSendServerVersion(false);
432     httpServer.setSendDateHeader(false);
433     httpServer.setStopAtShutdown(true);
434 
435     LOG.info("Starting Thrift HTTP Server on " + Integer.toString(listenPort));
436   }
437 
438   /**
439    * Setting up the thrift TServer
440    */
441   private void setupServer() throws Exception {
442     // Construct correct ProtocolFactory
443     TProtocolFactory protocolFactory;
444     if (conf.getBoolean(COMPACT_CONF_KEY, false)) {
445       LOG.debug("Using compact protocol");
446       protocolFactory = new TCompactProtocol.Factory();
447     } else {
448       LOG.debug("Using binary protocol");
449       protocolFactory = new TBinaryProtocol.Factory();
450     }
451 
452     final TProcessor p = new Hbase.Processor<Hbase.Iface>(handler);
453     ImplType implType = ImplType.getServerImpl(conf);
454     TProcessor processor = p;
455 
456     // Construct correct TransportFactory
457     TTransportFactory transportFactory;
458     if (conf.getBoolean(FRAMED_CONF_KEY, false) || implType.isAlwaysFramed) {
459       if (qop != null) {
460         throw new RuntimeException("Thrift server authentication"
461           + " doesn't work with framed transport yet");
462       }
463       transportFactory = new TFramedTransport.Factory(
464           conf.getInt(MAX_FRAME_SIZE_CONF_KEY, 2)  * 1024 * 1024);
465       LOG.debug("Using framed transport");
466     } else if (qop == null) {
467       transportFactory = new TTransportFactory();
468     } else {
469       // Extract the name from the principal
470       String name = SecurityUtil.getUserFromPrincipal(
471         conf.get("hbase.thrift.kerberos.principal"));
472       Map<String, String> saslProperties = new HashMap<String, String>();
473       saslProperties.put(Sasl.QOP, qop);
474       TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
475       saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties,
476         new SaslGssCallbackHandler() {
477           @Override
478           public void handle(Callback[] callbacks)
479               throws UnsupportedCallbackException {
480             AuthorizeCallback ac = null;
481             for (Callback callback : callbacks) {
482               if (callback instanceof AuthorizeCallback) {
483                 ac = (AuthorizeCallback) callback;
484               } else {
485                 throw new UnsupportedCallbackException(callback,
486                     "Unrecognized SASL GSSAPI Callback");
487               }
488             }
489             if (ac != null) {
490               String authid = ac.getAuthenticationID();
491               String authzid = ac.getAuthorizationID();
492               if (!authid.equals(authzid)) {
493                 ac.setAuthorized(false);
494               } else {
495                 ac.setAuthorized(true);
496                 String userName = SecurityUtil.getUserFromPrincipal(authzid);
497                 LOG.info("Effective user: " + userName);
498                 ac.setAuthorizedID(userName);
499               }
500             }
501           }
502         });
503       transportFactory = saslFactory;
504 
505       // Create a processor wrapper, to get the caller
506       processor = new TProcessor() {
507         @Override
508         public boolean process(TProtocol inProt,
509             TProtocol outProt) throws TException {
510           TSaslServerTransport saslServerTransport =
511             (TSaslServerTransport)inProt.getTransport();
512           SaslServer saslServer = saslServerTransport.getSaslServer();
513           String principal = saslServer.getAuthorizationID();
514           hbaseHandler.setEffectiveUser(principal);
515           return p.process(inProt, outProt);
516         }
517       };
518     }
519 
520     if (conf.get(BIND_CONF_KEY) != null && !implType.canSpecifyBindIP) {
521       LOG.error("Server types " + Joiner.on(", ").join(
522           ImplType.serversThatCannotSpecifyBindIP()) + " don't support IP " +
523           "address binding at the moment. See " +
524           "https://issues.apache.org/jira/browse/HBASE-2155 for details.");
525       throw new RuntimeException(
526           "-" + BIND_CONF_KEY + " not supported with " + implType);
527     }
528 
529     // Thrift's implementation uses '0' as a placeholder for 'use the default.'
530     int backlog = conf.getInt(BACKLOG_CONF_KEY, 0);
531 
532     if (implType == ImplType.HS_HA || implType == ImplType.NONBLOCKING ||
533         implType == ImplType.THREADED_SELECTOR) {
534       InetAddress listenAddress = getBindAddress(conf);
535       TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(
536           new InetSocketAddress(listenAddress, listenPort));
537 
538       if (implType == ImplType.NONBLOCKING) {
539         TNonblockingServer.Args serverArgs =
540             new TNonblockingServer.Args(serverTransport);
541         serverArgs.processor(processor)
542                   .transportFactory(transportFactory)
543                   .protocolFactory(protocolFactory);
544         tserver = new TNonblockingServer(serverArgs);
545       } else if (implType == ImplType.HS_HA) {
546         THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
547         CallQueue callQueue =
548             new CallQueue(new LinkedBlockingQueue<Call>(), metrics);
549         ExecutorService executorService = createExecutor(
550             callQueue, serverArgs.getMinWorkerThreads(), serverArgs.getMaxWorkerThreads());
551         serverArgs.executorService(executorService)
552                   .processor(processor)
553                   .transportFactory(transportFactory)
554                   .protocolFactory(protocolFactory);
555         tserver = new THsHaServer(serverArgs);
556       } else { // THREADED_SELECTOR
557         TThreadedSelectorServer.Args serverArgs =
558             new HThreadedSelectorServerArgs(serverTransport, conf);
559         CallQueue callQueue =
560             new CallQueue(new LinkedBlockingQueue<Call>(), metrics);
561         ExecutorService executorService = createExecutor(
562             callQueue, serverArgs.getWorkerThreads(), serverArgs.getWorkerThreads());
563         serverArgs.executorService(executorService)
564                   .processor(processor)
565                   .transportFactory(transportFactory)
566                   .protocolFactory(protocolFactory);
567         tserver = new TThreadedSelectorServer(serverArgs);
568       }
569       LOG.info("starting HBase " + implType.simpleClassName() +
570           " server on " + Integer.toString(listenPort));
571     } else if (implType == ImplType.THREAD_POOL) {
572       // Thread pool server. Get the IP address to bind to.
573       InetAddress listenAddress = getBindAddress(conf);
574       int readTimeout = conf.getInt(THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY,
575           THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT);
576       TServerTransport serverTransport = new TServerSocket(
577           new TServerSocket.ServerSocketTransportArgs().
578               bindAddr(new InetSocketAddress(listenAddress, listenPort)).
579               backlog(backlog).
580               clientTimeout(readTimeout));
581 
582       TBoundedThreadPoolServer.Args serverArgs =
583           new TBoundedThreadPoolServer.Args(serverTransport, conf);
584       serverArgs.processor(processor)
585                 .transportFactory(transportFactory)
586                 .protocolFactory(protocolFactory);
587       LOG.info("starting " + ImplType.THREAD_POOL.simpleClassName() + " on "
588           + listenAddress + ":" + Integer.toString(listenPort)
589           + " with readTimeout " + readTimeout + "ms; " + serverArgs);
590       TBoundedThreadPoolServer tserver =
591           new TBoundedThreadPoolServer(serverArgs, metrics);
592       this.tserver = tserver;
593     } else {
594       throw new AssertionError("Unsupported Thrift server implementation: " +
595           implType.simpleClassName());
596     }
597 
598     // A sanity check that we instantiated the right type of server.
599     if (tserver.getClass() != implType.serverClass) {
600       throw new AssertionError("Expected to create Thrift server class " +
601           implType.serverClass.getName() + " but got " +
602           tserver.getClass().getName());
603     }
604 
605 
606 
607     registerFilters(conf);
608   }
609 
610   ExecutorService createExecutor(BlockingQueue<Runnable> callQueue,
611                                  int minWorkers, int maxWorkers) {
612     ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
613     tfb.setDaemon(true);
614     tfb.setNameFormat("thrift-worker-%d");
615     return new ThreadPoolExecutor(minWorkers, maxWorkers,
616             Long.MAX_VALUE, TimeUnit.SECONDS, callQueue, tfb.build());
617   }
618 
619   private InetAddress getBindAddress(Configuration conf)
620       throws UnknownHostException {
621     String bindAddressStr = conf.get(BIND_CONF_KEY, DEFAULT_BIND_ADDR);
622     return InetAddress.getByName(bindAddressStr);
623   }
624 
625   protected static class ResultScannerWrapper {
626 
627     private final ResultScanner scanner;
628     private final boolean sortColumns;
629     public ResultScannerWrapper(ResultScanner resultScanner,
630                                 boolean sortResultColumns) {
631       scanner = resultScanner;
632       sortColumns = sortResultColumns;
633    }
634 
635     public ResultScanner getScanner() {
636       return scanner;
637     }
638 
639     public boolean isColumnSorted() {
640       return sortColumns;
641     }
642   }
643 
644   /**
645    * The HBaseHandler is a glue object that connects Thrift RPC calls to the
646    * HBase client API primarily defined in the Admin and Table objects.
647    */
648   public static class HBaseHandler implements Hbase.Iface {
649     protected Configuration conf;
650     protected static final Log LOG = LogFactory.getLog(HBaseHandler.class);
651 
652     // nextScannerId and scannerMap are used to manage scanner state
653     protected int nextScannerId = 0;
654     protected HashMap<Integer, ResultScannerWrapper> scannerMap = null;
655     private ThriftMetrics metrics = null;
656 
657     private final ConnectionCache connectionCache;
658     IncrementCoalescer coalescer = null;
659 
660     static final String CLEANUP_INTERVAL = "hbase.thrift.connection.cleanup-interval";
661     static final String MAX_IDLETIME = "hbase.thrift.connection.max-idletime";
662 
663     /**
664      * Returns a list of all the column families for a given Table.
665      *
666      * @param table
667      * @throws IOException
668      */
669     byte[][] getAllColumns(Table table) throws IOException {
670       HColumnDescriptor[] cds = table.getTableDescriptor().getColumnFamilies();
671       byte[][] columns = new byte[cds.length][];
672       for (int i = 0; i < cds.length; i++) {
673         columns[i] = Bytes.add(cds[i].getName(),
674             KeyValue.COLUMN_FAMILY_DELIM_ARRAY);
675       }
676       return columns;
677     }
678 
679     /**
680      * Creates and returns a Table instance from a given table name.
681      *
682      * @param tableName
683      *          name of table
684      * @return Table object
685      * @throws IOException
686      */
687     public Table getTable(final byte[] tableName) throws
688         IOException {
689       String table = Bytes.toString(tableName);
690       return connectionCache.getTable(table);
691     }
692 
693     public Table getTable(final ByteBuffer tableName) throws IOException {
694       return getTable(getBytes(tableName));
695     }
696 
697     /**
698      * Assigns a unique ID to the scanner and adds the mapping to an internal
699      * hash-map.
700      *
701      * @param scanner
702      * @return integer scanner id
703      */
704     protected synchronized int addScanner(ResultScanner scanner,boolean sortColumns) {
705       int id = nextScannerId++;
706       ResultScannerWrapper resultScannerWrapper = new ResultScannerWrapper(scanner, sortColumns);
707       scannerMap.put(id, resultScannerWrapper);
708       return id;
709     }
710 
711     /**
712      * Returns the scanner associated with the specified ID.
713      *
714      * @param id
715      * @return a Scanner, or null if ID was invalid.
716      */
717     protected synchronized ResultScannerWrapper getScanner(int id) {
718       return scannerMap.get(id);
719     }
720 
721     /**
722      * Removes the scanner associated with the specified ID from the internal
723      * id-&gt;scanner hash-map.
724      *
725      * @param id
726      * @return a Scanner, or null if ID was invalid.
727      */
728     protected synchronized ResultScannerWrapper removeScanner(int id) {
729       return scannerMap.remove(id);
730     }
731 
732     protected HBaseHandler(final Configuration c,
733         final UserProvider userProvider) throws IOException {
734       this.conf = c;
735       scannerMap = new HashMap<Integer, ResultScannerWrapper>();
736       this.coalescer = new IncrementCoalescer(this);
737 
738       int cleanInterval = conf.getInt(CLEANUP_INTERVAL, 10 * 1000);
739       int maxIdleTime = conf.getInt(MAX_IDLETIME, 10 * 60 * 1000);
740       connectionCache = new ConnectionCache(
741         conf, userProvider, cleanInterval, maxIdleTime);
742     }
743 
744     /**
745      * Obtain HBaseAdmin. Creates the instance if it is not already created.
746      */
747     private Admin getAdmin() throws IOException {
748       return connectionCache.getAdmin();
749     }
750 
751     void setEffectiveUser(String effectiveUser) {
752       connectionCache.setEffectiveUser(effectiveUser);
753     }
754 
755     @Override
756     public void enableTable(ByteBuffer tableName) throws IOError {
757       try{
758         getAdmin().enableTable(getTableName(tableName));
759       } catch (IOException e) {
760         LOG.warn(e.getMessage(), e);
761         throw new IOError(Throwables.getStackTraceAsString(e));
762       }
763     }
764 
765     @Override
766     public void disableTable(ByteBuffer tableName) throws IOError{
767       try{
768         getAdmin().disableTable(getTableName(tableName));
769       } catch (IOException e) {
770         LOG.warn(e.getMessage(), e);
771         throw new IOError(Throwables.getStackTraceAsString(e));
772       }
773     }
774 
775     @Override
776     public boolean isTableEnabled(ByteBuffer tableName) throws IOError {
777       try {
778         return this.connectionCache.getAdmin().isTableEnabled(getTableName(tableName));
779       } catch (IOException e) {
780         LOG.warn(e.getMessage(), e);
781         throw new IOError(Throwables.getStackTraceAsString(e));
782       }
783     }
784 
785     // ThriftServerRunner.compact should be deprecated and replaced with methods specific to
786     // table and region.
787     @Override
788     public void compact(ByteBuffer tableNameOrRegionName) throws IOError {
789       try {
790         try {
791           getAdmin().compactRegion(getBytes(tableNameOrRegionName));
792         } catch (IllegalArgumentException e) {
793           // Invalid region, try table
794           getAdmin().compact(TableName.valueOf(getBytes(tableNameOrRegionName)));
795         }
796       } catch (IOException e) {
797         LOG.warn(e.getMessage(), e);
798         throw new IOError(Throwables.getStackTraceAsString(e));
799       }
800     }
801 
802     // ThriftServerRunner.majorCompact should be deprecated and replaced with methods specific
803     // to table and region.
804     @Override
805     public void majorCompact(ByteBuffer tableNameOrRegionName) throws IOError {
806       try {
807         try {
808           getAdmin().compactRegion(getBytes(tableNameOrRegionName));
809         } catch (IllegalArgumentException e) {
810           // Invalid region, try table
811           getAdmin().compact(TableName.valueOf(getBytes(tableNameOrRegionName)));
812         }
813       } catch (IOException e) {
814         LOG.warn(e.getMessage(), e);
815         throw new IOError(Throwables.getStackTraceAsString(e));
816       }
817     }
818 
819     @Override
820     public List<ByteBuffer> getTableNames() throws IOError {
821       try {
822         TableName[] tableNames = this.getAdmin().listTableNames();
823         ArrayList<ByteBuffer> list = new ArrayList<ByteBuffer>(tableNames.length);
824         for (int i = 0; i < tableNames.length; i++) {
825           list.add(ByteBuffer.wrap(tableNames[i].getName()));
826         }
827         return list;
828       } catch (IOException e) {
829         LOG.warn(e.getMessage(), e);
830         throw new IOError(Throwables.getStackTraceAsString(e));
831       }
832     }
833 
834     /**
835      * @return the list of regions in the given table, or an empty list if the table does not exist
836      */
837     @Override
838     public List<TRegionInfo> getTableRegions(ByteBuffer tableName)
839     throws IOError {
840       try (RegionLocator locator = connectionCache.getRegionLocator(getBytes(tableName))) {
841         List<HRegionLocation> regionLocations = locator.getAllRegionLocations();
842         List<TRegionInfo> results = new ArrayList<TRegionInfo>();
843         for (HRegionLocation regionLocation : regionLocations) {
844           HRegionInfo info = regionLocation.getRegionInfo();
845           ServerName serverName = regionLocation.getServerName();
846           TRegionInfo region = new TRegionInfo();
847           region.serverName = ByteBuffer.wrap(
848               Bytes.toBytes(serverName.getHostname()));
849           region.port = serverName.getPort();
850           region.startKey = ByteBuffer.wrap(info.getStartKey());
851           region.endKey = ByteBuffer.wrap(info.getEndKey());
852           region.id = info.getRegionId();
853           region.name = ByteBuffer.wrap(info.getRegionName());
854           region.version = HREGION_VERSION; // HRegion now not versioned, PB encoding used
855           results.add(region);
856         }
857         return results;
858       } catch (TableNotFoundException e) {
859         // Return empty list for non-existing table
860         return Collections.emptyList();
861       } catch (IOException e){
862         LOG.warn(e.getMessage(), e);
863         throw new IOError(Throwables.getStackTraceAsString(e));
864       }
865     }
866 
867     @Override
868     public List<TCell> get(
869         ByteBuffer tableName, ByteBuffer row, ByteBuffer column,
870         Map<ByteBuffer, ByteBuffer> attributes)
871         throws IOError {
872       byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
873       if (famAndQf.length == 1) {
874         return get(tableName, row, famAndQf[0], null, attributes);
875       }
876       if (famAndQf.length == 2) {
877         return get(tableName, row, famAndQf[0], famAndQf[1], attributes);
878       }
879       throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
880     }
881 
882     /**
883      * Note: this internal interface is slightly different from public APIs in regard to handling
884      * of the qualifier. Here we differ from the public Java API in that null != byte[0]. Rather,
885      * we respect qual == null as a request for the entire column family. The caller (
886      * {@link #get(ByteBuffer, ByteBuffer, ByteBuffer, Map)}) interface IS consistent in that the
887      * column is parse like normal.
888      */
889     protected List<TCell> get(ByteBuffer tableName,
890                               ByteBuffer row,
891                               byte[] family,
892                               byte[] qualifier,
893                               Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
894       Table table = null;
895       try {
896         table = getTable(tableName);
897         Get get = new Get(getBytes(row));
898         addAttributes(get, attributes);
899         if (qualifier == null) {
900           get.addFamily(family);
901         } else {
902           get.addColumn(family, qualifier);
903         }
904         Result result = table.get(get);
905         return ThriftUtilities.cellFromHBase(result.rawCells());
906       } catch (IOException e) {
907         LOG.warn(e.getMessage(), e);
908         throw new IOError(Throwables.getStackTraceAsString(e));
909       } finally {
910         closeTable(table);
911       }
912     }
913 
914     @Override
915     public List<TCell> getVer(ByteBuffer tableName, ByteBuffer row, ByteBuffer column,
916         int numVersions, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
917       byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
918       if(famAndQf.length == 1) {
919         return getVer(tableName, row, famAndQf[0], null, numVersions, attributes);
920       }
921       if (famAndQf.length == 2) {
922         return getVer(tableName, row, famAndQf[0], famAndQf[1], numVersions, attributes);
923       }
924       throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
925 
926     }
927 
928     /**
929      * Note: this public interface is slightly different from public Java APIs in regard to
930      * handling of the qualifier. Here we differ from the public Java API in that null != byte[0].
931      * Rather, we respect qual == null as a request for the entire column family. If you want to
932      * access the entire column family, use
933      * {@link #getVer(ByteBuffer, ByteBuffer, ByteBuffer, int, Map)} with a {@code column} value
934      * that lacks a {@code ':'}.
935      */
936     public List<TCell> getVer(ByteBuffer tableName, ByteBuffer row, byte[] family,
937         byte[] qualifier, int numVersions, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
938       
939       Table table = null;
940       try {
941         table = getTable(tableName);
942         Get get = new Get(getBytes(row));
943         addAttributes(get, attributes);
944         if (null == qualifier) {
945           get.addFamily(family);
946         } else {
947           get.addColumn(family, qualifier);
948         }
949         get.setMaxVersions(numVersions);
950         Result result = table.get(get);
951         return ThriftUtilities.cellFromHBase(result.rawCells());
952       } catch (IOException e) {
953         LOG.warn(e.getMessage(), e);
954         throw new IOError(Throwables.getStackTraceAsString(e));
955       } finally{
956         closeTable(table);
957       }
958     }
959 
960     @Override
961     public List<TCell> getVerTs(ByteBuffer tableName, ByteBuffer row, ByteBuffer column,
962         long timestamp, int numVersions, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
963       byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
964       if (famAndQf.length == 1) {
965         return getVerTs(tableName, row, famAndQf[0], null, timestamp, numVersions, attributes);
966       }
967       if (famAndQf.length == 2) {
968         return getVerTs(tableName, row, famAndQf[0], famAndQf[1], timestamp, numVersions,
969           attributes);
970       }
971       throw new IllegalArgumentException("Invalid familyAndQualifier provided.");
972     }
973 
974     /**
975      * Note: this internal interface is slightly different from public APIs in regard to handling
976      * of the qualifier. Here we differ from the public Java API in that null != byte[0]. Rather,
977      * we respect qual == null as a request for the entire column family. The caller (
978      * {@link #getVerTs(ByteBuffer, ByteBuffer, ByteBuffer, long, int, Map)}) interface IS
979      * consistent in that the column is parse like normal.
980      */
981     protected List<TCell> getVerTs(ByteBuffer tableName, ByteBuffer row, byte[] family,
982         byte[] qualifier, long timestamp, int numVersions, Map<ByteBuffer, ByteBuffer> attributes)
983         throws IOError {
984       
985       Table table = null;
986       try {
987         table = getTable(tableName);
988         Get get = new Get(getBytes(row));
989         addAttributes(get, attributes);
990         if (null == qualifier) {
991           get.addFamily(family);
992         } else {
993           get.addColumn(family, qualifier);
994         }
995         get.setTimeRange(0, timestamp);
996         get.setMaxVersions(numVersions);
997         Result result = table.get(get);
998         return ThriftUtilities.cellFromHBase(result.rawCells());
999       } catch (IOException e) {
1000         LOG.warn(e.getMessage(), e);
1001         throw new IOError(Throwables.getStackTraceAsString(e));
1002       } finally{
1003         closeTable(table);
1004       }
1005     }
1006 
1007     @Override
1008     public List<TRowResult> getRow(ByteBuffer tableName, ByteBuffer row,
1009         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1010       return getRowWithColumnsTs(tableName, row, null,
1011                                  HConstants.LATEST_TIMESTAMP,
1012                                  attributes);
1013     }
1014 
1015     @Override
1016     public List<TRowResult> getRowWithColumns(ByteBuffer tableName,
1017                                               ByteBuffer row,
1018         List<ByteBuffer> columns,
1019         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1020       return getRowWithColumnsTs(tableName, row, columns,
1021                                  HConstants.LATEST_TIMESTAMP,
1022                                  attributes);
1023     }
1024 
1025     @Override
1026     public List<TRowResult> getRowTs(ByteBuffer tableName, ByteBuffer row,
1027         long timestamp, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1028       return getRowWithColumnsTs(tableName, row, null,
1029                                  timestamp, attributes);
1030     }
1031 
1032     @Override
1033     public List<TRowResult> getRowWithColumnsTs(
1034         ByteBuffer tableName, ByteBuffer row, List<ByteBuffer> columns,
1035         long timestamp, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1036       
1037       Table table = null;
1038       try {
1039         table = getTable(tableName);
1040         if (columns == null) {
1041           Get get = new Get(getBytes(row));
1042           addAttributes(get, attributes);
1043           get.setTimeRange(0, timestamp);
1044           Result result = table.get(get);
1045           return ThriftUtilities.rowResultFromHBase(result);
1046         }
1047         Get get = new Get(getBytes(row));
1048         addAttributes(get, attributes);
1049         for(ByteBuffer column : columns) {
1050           byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
1051           if (famAndQf.length == 1) {
1052               get.addFamily(famAndQf[0]);
1053           } else {
1054               get.addColumn(famAndQf[0], famAndQf[1]);
1055           }
1056         }
1057         get.setTimeRange(0, timestamp);
1058         Result result = table.get(get);
1059         return ThriftUtilities.rowResultFromHBase(result);
1060       } catch (IOException e) {
1061         LOG.warn(e.getMessage(), e);
1062         throw new IOError(Throwables.getStackTraceAsString(e));
1063       } finally{
1064         closeTable(table);
1065       }
1066     }
1067 
1068     @Override
1069     public List<TRowResult> getRows(ByteBuffer tableName,
1070                                     List<ByteBuffer> rows,
1071         Map<ByteBuffer, ByteBuffer> attributes)
1072         throws IOError {
1073       return getRowsWithColumnsTs(tableName, rows, null,
1074                                   HConstants.LATEST_TIMESTAMP,
1075                                   attributes);
1076     }
1077 
1078     @Override
1079     public List<TRowResult> getRowsWithColumns(ByteBuffer tableName,
1080                                                List<ByteBuffer> rows,
1081         List<ByteBuffer> columns,
1082         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1083       return getRowsWithColumnsTs(tableName, rows, columns,
1084                                   HConstants.LATEST_TIMESTAMP,
1085                                   attributes);
1086     }
1087 
1088     @Override
1089     public List<TRowResult> getRowsTs(ByteBuffer tableName,
1090                                       List<ByteBuffer> rows,
1091         long timestamp,
1092         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1093       return getRowsWithColumnsTs(tableName, rows, null,
1094                                   timestamp, attributes);
1095     }
1096 
1097     @Override
1098     public List<TRowResult> getRowsWithColumnsTs(ByteBuffer tableName,
1099                                                  List<ByteBuffer> rows,
1100         List<ByteBuffer> columns, long timestamp,
1101         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1102       
1103       Table table= null;
1104       try {
1105         List<Get> gets = new ArrayList<Get>(rows.size());
1106         table = getTable(tableName);
1107         if (metrics != null) {
1108           metrics.incNumRowKeysInBatchGet(rows.size());
1109         }
1110         for (ByteBuffer row : rows) {
1111           Get get = new Get(getBytes(row));
1112           addAttributes(get, attributes);
1113           if (columns != null) {
1114 
1115             for(ByteBuffer column : columns) {
1116               byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
1117               if (famAndQf.length == 1) {
1118                 get.addFamily(famAndQf[0]);
1119               } else {
1120                 get.addColumn(famAndQf[0], famAndQf[1]);
1121               }
1122             }
1123           }
1124           get.setTimeRange(0, timestamp);
1125           gets.add(get);
1126         }
1127         Result[] result = table.get(gets);
1128         return ThriftUtilities.rowResultFromHBase(result);
1129       } catch (IOException e) {
1130         LOG.warn(e.getMessage(), e);
1131         throw new IOError(Throwables.getStackTraceAsString(e));
1132       } finally{
1133         closeTable(table);
1134       }
1135     }
1136 
1137     @Override
1138     public void deleteAll(
1139         ByteBuffer tableName, ByteBuffer row, ByteBuffer column,
1140         Map<ByteBuffer, ByteBuffer> attributes)
1141         throws IOError {
1142       deleteAllTs(tableName, row, column, HConstants.LATEST_TIMESTAMP,
1143                   attributes);
1144     }
1145 
1146     @Override
1147     public void deleteAllTs(ByteBuffer tableName,
1148                             ByteBuffer row,
1149                             ByteBuffer column,
1150         long timestamp, Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1151       Table table = null;
1152       try {
1153         table = getTable(tableName);
1154         Delete delete  = new Delete(getBytes(row));
1155         addAttributes(delete, attributes);
1156         byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
1157         if (famAndQf.length == 1) {
1158           delete.addFamily(famAndQf[0], timestamp);
1159         } else {
1160           delete.addColumns(famAndQf[0], famAndQf[1], timestamp);
1161         }
1162         table.delete(delete);
1163 
1164       } catch (IOException e) {
1165         LOG.warn(e.getMessage(), e);
1166         throw new IOError(Throwables.getStackTraceAsString(e));
1167       } finally {
1168         closeTable(table);
1169       }
1170     }
1171 
1172     @Override
1173     public void deleteAllRow(
1174         ByteBuffer tableName, ByteBuffer row,
1175         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1176       deleteAllRowTs(tableName, row, HConstants.LATEST_TIMESTAMP, attributes);
1177     }
1178 
1179     @Override
1180     public void deleteAllRowTs(
1181         ByteBuffer tableName, ByteBuffer row, long timestamp,
1182         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1183       Table table = null;
1184       try {
1185         table = getTable(tableName);
1186         Delete delete  = new Delete(getBytes(row), timestamp);
1187         addAttributes(delete, attributes);
1188         table.delete(delete);
1189       } catch (IOException e) {
1190         LOG.warn(e.getMessage(), e);
1191         throw new IOError(Throwables.getStackTraceAsString(e));
1192       } finally {
1193         closeTable(table);
1194       }
1195     }
1196 
1197     @Override
1198     public void createTable(ByteBuffer in_tableName,
1199         List<ColumnDescriptor> columnFamilies) throws IOError,
1200         IllegalArgument, AlreadyExists {
1201       TableName tableName = getTableName(in_tableName);
1202       try {
1203         if (getAdmin().tableExists(tableName)) {
1204           throw new AlreadyExists("table name already in use");
1205         }
1206         HTableDescriptor desc = new HTableDescriptor(tableName);
1207         for (ColumnDescriptor col : columnFamilies) {
1208           HColumnDescriptor colDesc = ThriftUtilities.colDescFromThrift(col);
1209           desc.addFamily(colDesc);
1210         }
1211         getAdmin().createTable(desc);
1212       } catch (IOException e) {
1213         LOG.warn(e.getMessage(), e);
1214         throw new IOError(Throwables.getStackTraceAsString(e));
1215       } catch (IllegalArgumentException e) {
1216         LOG.warn(e.getMessage(), e);
1217         throw new IllegalArgument(Throwables.getStackTraceAsString(e));
1218       }
1219     }
1220 
1221     private static TableName getTableName(ByteBuffer buffer) {
1222       return TableName.valueOf(getBytes(buffer));
1223     }
1224 
1225     @Override
1226     public void deleteTable(ByteBuffer in_tableName) throws IOError {
1227       TableName tableName = getTableName(in_tableName);
1228       if (LOG.isDebugEnabled()) {
1229         LOG.debug("deleteTable: table=" + tableName);
1230       }
1231       try {
1232         if (!getAdmin().tableExists(tableName)) {
1233           throw new IOException("table does not exist");
1234         }
1235         getAdmin().deleteTable(tableName);
1236       } catch (IOException e) {
1237         LOG.warn(e.getMessage(), e);
1238         throw new IOError(Throwables.getStackTraceAsString(e));
1239       }
1240     }
1241 
1242     @Override
1243     public void mutateRow(ByteBuffer tableName, ByteBuffer row,
1244         List<Mutation> mutations, Map<ByteBuffer, ByteBuffer> attributes)
1245         throws IOError, IllegalArgument {
1246       mutateRowTs(tableName, row, mutations, HConstants.LATEST_TIMESTAMP,
1247                   attributes);
1248     }
1249 
1250     @Override
1251     public void mutateRowTs(ByteBuffer tableName, ByteBuffer row,
1252         List<Mutation> mutations, long timestamp,
1253         Map<ByteBuffer, ByteBuffer> attributes)
1254         throws IOError, IllegalArgument {
1255       Table table = null;
1256       try {
1257         table = getTable(tableName);
1258         Put put = new Put(getBytes(row), timestamp);
1259         addAttributes(put, attributes);
1260 
1261         Delete delete = new Delete(getBytes(row));
1262         addAttributes(delete, attributes);
1263         if (metrics != null) {
1264           metrics.incNumRowKeysInBatchMutate(mutations.size());
1265         }
1266 
1267         // I apologize for all this mess :)
1268         for (Mutation m : mutations) {
1269           byte[][] famAndQf = KeyValue.parseColumn(getBytes(m.column));
1270           if (m.isDelete) {
1271             if (famAndQf.length == 1) {
1272               delete.addFamily(famAndQf[0], timestamp);
1273             } else {
1274               delete.addColumns(famAndQf[0], famAndQf[1], timestamp);
1275             }
1276             delete.setDurability(m.writeToWAL ? Durability.SYNC_WAL
1277                 : Durability.SKIP_WAL);
1278           } else {
1279             if(famAndQf.length == 1) {
1280               LOG.warn("No column qualifier specified. Delete is the only mutation supported "
1281                   + "over the whole column family.");
1282             } else {
1283               put.addImmutable(famAndQf[0], famAndQf[1],
1284                   m.value != null ? getBytes(m.value)
1285                       : HConstants.EMPTY_BYTE_ARRAY);
1286             }
1287             put.setDurability(m.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL);
1288           }
1289         }
1290         if (!delete.isEmpty())
1291           table.delete(delete);
1292         if (!put.isEmpty())
1293           table.put(put);
1294       } catch (IOException e) {
1295         LOG.warn(e.getMessage(), e);
1296         throw new IOError(Throwables.getStackTraceAsString(e));
1297       } catch (IllegalArgumentException e) {
1298         LOG.warn(e.getMessage(), e);
1299         throw new IllegalArgument(Throwables.getStackTraceAsString(e));
1300       } finally{
1301         closeTable(table);
1302       }
1303     }
1304 
1305     @Override
1306     public void mutateRows(ByteBuffer tableName, List<BatchMutation> rowBatches,
1307         Map<ByteBuffer, ByteBuffer> attributes)
1308         throws IOError, IllegalArgument, TException {
1309       mutateRowsTs(tableName, rowBatches, HConstants.LATEST_TIMESTAMP, attributes);
1310     }
1311 
1312     @Override
1313     public void mutateRowsTs(
1314         ByteBuffer tableName, List<BatchMutation> rowBatches, long timestamp,
1315         Map<ByteBuffer, ByteBuffer> attributes)
1316         throws IOError, IllegalArgument, TException {
1317       List<Put> puts = new ArrayList<Put>();
1318       List<Delete> deletes = new ArrayList<Delete>();
1319 
1320       for (BatchMutation batch : rowBatches) {
1321         byte[] row = getBytes(batch.row);
1322         List<Mutation> mutations = batch.mutations;
1323         Delete delete = new Delete(row);
1324         addAttributes(delete, attributes);
1325         Put put = new Put(row, timestamp);
1326         addAttributes(put, attributes);
1327         for (Mutation m : mutations) {
1328           byte[][] famAndQf = KeyValue.parseColumn(getBytes(m.column));
1329           if (m.isDelete) {
1330             // no qualifier, family only.
1331             if (famAndQf.length == 1) {
1332               delete.addFamily(famAndQf[0], timestamp);
1333             } else {
1334               delete.addColumns(famAndQf[0], famAndQf[1], timestamp);
1335             }
1336             delete.setDurability(m.writeToWAL ? Durability.SYNC_WAL
1337                 : Durability.SKIP_WAL);
1338           } else {
1339             if (famAndQf.length == 1) {
1340               LOG.warn("No column qualifier specified. Delete is the only mutation supported "
1341                   + "over the whole column family.");
1342             }
1343             if (famAndQf.length == 2) {
1344               put.addImmutable(famAndQf[0], famAndQf[1],
1345                   m.value != null ? getBytes(m.value)
1346                       : HConstants.EMPTY_BYTE_ARRAY);
1347             } else {
1348               throw new IllegalArgumentException("Invalid famAndQf provided.");
1349             }
1350             put.setDurability(m.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL);
1351           }
1352         }
1353         if (!delete.isEmpty())
1354           deletes.add(delete);
1355         if (!put.isEmpty())
1356           puts.add(put);
1357       }
1358 
1359       Table table = null;
1360       try {
1361         table = getTable(tableName);
1362         if (!puts.isEmpty())
1363           table.put(puts);
1364         if (!deletes.isEmpty())
1365           table.delete(deletes);
1366 
1367       } catch (IOException e) {
1368         LOG.warn(e.getMessage(), e);
1369         throw new IOError(Throwables.getStackTraceAsString(e));
1370       } catch (IllegalArgumentException e) {
1371         LOG.warn(e.getMessage(), e);
1372         throw new IllegalArgument(Throwables.getStackTraceAsString(e));
1373       } finally{
1374         closeTable(table);
1375       }
1376     }
1377 
1378     @Override
1379     public long atomicIncrement(
1380         ByteBuffer tableName, ByteBuffer row, ByteBuffer column, long amount)
1381             throws IOError, IllegalArgument, TException {
1382       byte [][] famAndQf = KeyValue.parseColumn(getBytes(column));
1383       if(famAndQf.length == 1) {
1384         return atomicIncrement(tableName, row, famAndQf[0], HConstants.EMPTY_BYTE_ARRAY, amount);
1385       }
1386       return atomicIncrement(tableName, row, famAndQf[0], famAndQf[1], amount);
1387     }
1388 
1389     protected long atomicIncrement(ByteBuffer tableName, ByteBuffer row,
1390         byte [] family, byte [] qualifier, long amount)
1391         throws IOError, IllegalArgument, TException {
1392       Table table = null;
1393       try {
1394         table = getTable(tableName);
1395         return table.incrementColumnValue(
1396             getBytes(row), family, qualifier, amount);
1397       } catch (IOException e) {
1398         LOG.warn(e.getMessage(), e);
1399         throw new IOError(Throwables.getStackTraceAsString(e));
1400       } finally {
1401         closeTable(table);
1402       }
1403     }
1404 
1405     @Override
1406     public void scannerClose(int id) throws IOError, IllegalArgument {
1407       LOG.debug("scannerClose: id=" + id);
1408       ResultScannerWrapper resultScannerWrapper = getScanner(id);
1409       if (resultScannerWrapper == null) {
1410         String message = "scanner ID is invalid";
1411         LOG.warn(message);
1412         throw new IllegalArgument("scanner ID is invalid");
1413       }
1414       resultScannerWrapper.getScanner().close();
1415       removeScanner(id);
1416     }
1417 
1418     @Override
1419     public List<TRowResult> scannerGetList(int id,int nbRows)
1420         throws IllegalArgument, IOError {
1421       LOG.debug("scannerGetList: id=" + id);
1422       ResultScannerWrapper resultScannerWrapper = getScanner(id);
1423       if (null == resultScannerWrapper) {
1424         String message = "scanner ID is invalid";
1425         LOG.warn(message);
1426         throw new IllegalArgument("scanner ID is invalid");
1427       }
1428 
1429       Result [] results = null;
1430       try {
1431         results = resultScannerWrapper.getScanner().next(nbRows);
1432         if (null == results) {
1433           return new ArrayList<TRowResult>();
1434         }
1435       } catch (IOException e) {
1436         LOG.warn(e.getMessage(), e);
1437         throw new IOError(Throwables.getStackTraceAsString(e));
1438       }
1439       return ThriftUtilities.rowResultFromHBase(results, resultScannerWrapper.isColumnSorted());
1440     }
1441 
1442     @Override
1443     public List<TRowResult> scannerGet(int id) throws IllegalArgument, IOError {
1444       return scannerGetList(id,1);
1445     }
1446 
1447     @Override
1448     public int scannerOpenWithScan(ByteBuffer tableName, TScan tScan,
1449         Map<ByteBuffer, ByteBuffer> attributes)
1450         throws IOError {
1451       
1452       Table table = null;
1453       try {
1454         table = getTable(tableName);
1455         Scan scan = new Scan();
1456         addAttributes(scan, attributes);
1457         if (tScan.isSetStartRow()) {
1458           scan.setStartRow(tScan.getStartRow());
1459         }
1460         if (tScan.isSetStopRow()) {
1461           scan.setStopRow(tScan.getStopRow());
1462         }
1463         if (tScan.isSetTimestamp()) {
1464           scan.setTimeRange(0, tScan.getTimestamp());
1465         }
1466         if (tScan.isSetCaching()) {
1467           scan.setCaching(tScan.getCaching());
1468         }
1469         if (tScan.isSetBatchSize()) {
1470           scan.setBatch(tScan.getBatchSize());
1471         }
1472         if (tScan.isSetColumns() && tScan.getColumns().size() != 0) {
1473           for(ByteBuffer column : tScan.getColumns()) {
1474             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1475             if(famQf.length == 1) {
1476               scan.addFamily(famQf[0]);
1477             } else {
1478               scan.addColumn(famQf[0], famQf[1]);
1479             }
1480           }
1481         }
1482         if (tScan.isSetFilterString()) {
1483           ParseFilter parseFilter = new ParseFilter();
1484           scan.setFilter(
1485               parseFilter.parseFilterString(tScan.getFilterString()));
1486         }
1487         if (tScan.isSetReversed()) {
1488           scan.setReversed(tScan.isReversed());
1489         }
1490         return addScanner(table.getScanner(scan), tScan.sortColumns);
1491       } catch (IOException e) {
1492         LOG.warn(e.getMessage(), e);
1493         throw new IOError(Throwables.getStackTraceAsString(e));
1494       } finally{
1495         closeTable(table);
1496       }
1497     }
1498 
1499     @Override
1500     public int scannerOpen(ByteBuffer tableName, ByteBuffer startRow,
1501         List<ByteBuffer> columns,
1502         Map<ByteBuffer, ByteBuffer> attributes) throws IOError {
1503       
1504       Table table = null;
1505       try {
1506         table = getTable(tableName);
1507         Scan scan = new Scan(getBytes(startRow));
1508         addAttributes(scan, attributes);
1509         if(columns != null && columns.size() != 0) {
1510           for(ByteBuffer column : columns) {
1511             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1512             if(famQf.length == 1) {
1513               scan.addFamily(famQf[0]);
1514             } else {
1515               scan.addColumn(famQf[0], famQf[1]);
1516             }
1517           }
1518         }
1519         return addScanner(table.getScanner(scan), false);
1520       } catch (IOException e) {
1521         LOG.warn(e.getMessage(), e);
1522         throw new IOError(Throwables.getStackTraceAsString(e));
1523       } finally{
1524         closeTable(table);
1525       }
1526     }
1527 
1528     @Override
1529     public int scannerOpenWithStop(ByteBuffer tableName, ByteBuffer startRow,
1530         ByteBuffer stopRow, List<ByteBuffer> columns,
1531         Map<ByteBuffer, ByteBuffer> attributes)
1532         throws IOError, TException {
1533       
1534       Table table = null;
1535       try {
1536         table = getTable(tableName);
1537         Scan scan = new Scan(getBytes(startRow), getBytes(stopRow));
1538         addAttributes(scan, attributes);
1539         if(columns != null && columns.size() != 0) {
1540           for(ByteBuffer column : columns) {
1541             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1542             if(famQf.length == 1) {
1543               scan.addFamily(famQf[0]);
1544             } else {
1545               scan.addColumn(famQf[0], famQf[1]);
1546             }
1547           }
1548         }
1549         return addScanner(table.getScanner(scan), false);
1550       } catch (IOException e) {
1551         LOG.warn(e.getMessage(), e);
1552         throw new IOError(Throwables.getStackTraceAsString(e));
1553       } finally{
1554         closeTable(table);
1555       }
1556     }
1557 
1558     @Override
1559     public int scannerOpenWithPrefix(ByteBuffer tableName,
1560                                      ByteBuffer startAndPrefix,
1561                                      List<ByteBuffer> columns,
1562         Map<ByteBuffer, ByteBuffer> attributes)
1563         throws IOError, TException {
1564       
1565       Table table = null;
1566       try {
1567         table = getTable(tableName);
1568         Scan scan = new Scan(getBytes(startAndPrefix));
1569         addAttributes(scan, attributes);
1570         Filter f = new WhileMatchFilter(
1571             new PrefixFilter(getBytes(startAndPrefix)));
1572         scan.setFilter(f);
1573         if (columns != null && columns.size() != 0) {
1574           for(ByteBuffer column : columns) {
1575             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1576             if(famQf.length == 1) {
1577               scan.addFamily(famQf[0]);
1578             } else {
1579               scan.addColumn(famQf[0], famQf[1]);
1580             }
1581           }
1582         }
1583         return addScanner(table.getScanner(scan), false);
1584       } catch (IOException e) {
1585         LOG.warn(e.getMessage(), e);
1586         throw new IOError(Throwables.getStackTraceAsString(e));
1587       } finally{
1588         closeTable(table);
1589       }
1590     }
1591 
1592     @Override
1593     public int scannerOpenTs(ByteBuffer tableName, ByteBuffer startRow,
1594         List<ByteBuffer> columns, long timestamp,
1595         Map<ByteBuffer, ByteBuffer> attributes) throws IOError, TException {
1596       
1597       Table table = null;
1598       try {
1599         table = getTable(tableName);
1600         Scan scan = new Scan(getBytes(startRow));
1601         addAttributes(scan, attributes);
1602         scan.setTimeRange(0, timestamp);
1603         if (columns != null && columns.size() != 0) {
1604           for (ByteBuffer column : columns) {
1605             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1606             if(famQf.length == 1) {
1607               scan.addFamily(famQf[0]);
1608             } else {
1609               scan.addColumn(famQf[0], famQf[1]);
1610             }
1611           }
1612         }
1613         return addScanner(table.getScanner(scan), false);
1614       } catch (IOException e) {
1615         LOG.warn(e.getMessage(), e);
1616         throw new IOError(Throwables.getStackTraceAsString(e));
1617       } finally{
1618         closeTable(table);
1619       }
1620     }
1621 
1622     @Override
1623     public int scannerOpenWithStopTs(ByteBuffer tableName, ByteBuffer startRow,
1624         ByteBuffer stopRow, List<ByteBuffer> columns, long timestamp,
1625         Map<ByteBuffer, ByteBuffer> attributes)
1626         throws IOError, TException {
1627       
1628       Table table = null;
1629       try {
1630         table = getTable(tableName);
1631         Scan scan = new Scan(getBytes(startRow), getBytes(stopRow));
1632         addAttributes(scan, attributes);
1633         scan.setTimeRange(0, timestamp);
1634         if (columns != null && columns.size() != 0) {
1635           for (ByteBuffer column : columns) {
1636             byte [][] famQf = KeyValue.parseColumn(getBytes(column));
1637             if(famQf.length == 1) {
1638               scan.addFamily(famQf[0]);
1639             } else {
1640               scan.addColumn(famQf[0], famQf[1]);
1641             }
1642           }
1643         }
1644         scan.setTimeRange(0, timestamp);
1645         return addScanner(table.getScanner(scan), false);
1646       } catch (IOException e) {
1647         LOG.warn(e.getMessage(), e);
1648         throw new IOError(Throwables.getStackTraceAsString(e));
1649       } finally{
1650         closeTable(table);
1651       }
1652     }
1653 
1654     @Override
1655     public Map<ByteBuffer, ColumnDescriptor> getColumnDescriptors(
1656         ByteBuffer tableName) throws IOError, TException {
1657       
1658       Table table = null;
1659       try {
1660         TreeMap<ByteBuffer, ColumnDescriptor> columns =
1661           new TreeMap<ByteBuffer, ColumnDescriptor>();
1662 
1663         table = getTable(tableName);
1664         HTableDescriptor desc = table.getTableDescriptor();
1665 
1666         for (HColumnDescriptor e : desc.getFamilies()) {
1667           ColumnDescriptor col = ThriftUtilities.colDescFromHbase(e);
1668           columns.put(col.name, col);
1669         }
1670         return columns;
1671       } catch (IOException e) {
1672         LOG.warn(e.getMessage(), e);
1673         throw new IOError(Throwables.getStackTraceAsString(e));
1674       } finally {
1675         closeTable(table);
1676       }
1677     }
1678     
1679     private void closeTable(Table table) throws IOError
1680     {
1681       try{
1682         if(table != null){
1683           table.close();
1684         }
1685       } catch (IOException e){
1686         LOG.error(e.getMessage(), e);
1687         throw new IOError(Throwables.getStackTraceAsString(e));
1688       }
1689     }
1690     
1691     @Override
1692     public TRegionInfo getRegionInfo(ByteBuffer searchRow) throws IOError {
1693       try {
1694         byte[] row = getBytes(searchRow);
1695         Result startRowResult = getReverseScanResult(TableName.META_TABLE_NAME.getName(), row,
1696           HConstants.CATALOG_FAMILY);
1697 
1698         if (startRowResult == null) {
1699           throw new IOException("Cannot find row in "+ TableName.META_TABLE_NAME+", row="
1700                                 + Bytes.toStringBinary(row));
1701         }
1702 
1703         // find region start and end keys
1704         HRegionInfo regionInfo = MetaTableAccessor.getHRegionInfo(startRowResult);
1705         if (regionInfo == null) {
1706           throw new IOException("HRegionInfo REGIONINFO was null or " +
1707                                 " empty in Meta for row="
1708                                 + Bytes.toStringBinary(row));
1709         }
1710         TRegionInfo region = new TRegionInfo();
1711         region.setStartKey(regionInfo.getStartKey());
1712         region.setEndKey(regionInfo.getEndKey());
1713         region.id = regionInfo.getRegionId();
1714         region.setName(regionInfo.getRegionName());
1715         region.version = HREGION_VERSION; // version not used anymore, PB encoding used.
1716 
1717         // find region assignment to server
1718         ServerName serverName = MetaTableAccessor.getServerName(startRowResult, 0);
1719         if (serverName != null) {
1720           region.setServerName(Bytes.toBytes(serverName.getHostname()));
1721           region.port = serverName.getPort();
1722         }
1723         return region;
1724       } catch (IOException e) {
1725         LOG.warn(e.getMessage(), e);
1726         throw new IOError(Throwables.getStackTraceAsString(e));
1727       }
1728     }
1729 
1730     private Result getReverseScanResult(byte[] tableName, byte[] row, byte[] family)
1731         throws IOException {
1732       Scan scan = new Scan(row);
1733       scan.setReversed(true);
1734       scan.addFamily(family);
1735       scan.setStartRow(row);
1736       Table table = getTable(tableName);      
1737       try (ResultScanner scanner = table.getScanner(scan)) {
1738         return scanner.next();
1739       } finally{
1740         if(table != null){
1741           table.close();
1742         }
1743       }
1744     }
1745 
1746     private void initMetrics(ThriftMetrics metrics) {
1747       this.metrics = metrics;
1748     }
1749 
1750     @Override
1751     public void increment(TIncrement tincrement) throws IOError, TException {
1752 
1753       if (tincrement.getRow().length == 0 || tincrement.getTable().length == 0) {
1754         throw new TException("Must supply a table and a row key; can't increment");
1755       }
1756 
1757       if (conf.getBoolean(COALESCE_INC_KEY, false)) {
1758         this.coalescer.queueIncrement(tincrement);
1759         return;
1760       }
1761 
1762       Table table = null;
1763       try {
1764         table = getTable(tincrement.getTable());
1765         Increment inc = ThriftUtilities.incrementFromThrift(tincrement);
1766         table.increment(inc);
1767       } catch (IOException e) {
1768         LOG.warn(e.getMessage(), e);
1769         throw new IOError(Throwables.getStackTraceAsString(e));
1770       } finally{
1771         closeTable(table);
1772       }
1773     }
1774 
1775     @Override
1776     public void incrementRows(List<TIncrement> tincrements) throws IOError, TException {
1777       if (conf.getBoolean(COALESCE_INC_KEY, false)) {
1778         this.coalescer.queueIncrements(tincrements);
1779         return;
1780       }
1781       for (TIncrement tinc : tincrements) {
1782         increment(tinc);
1783       }
1784     }
1785 
1786     @Override
1787     public List<TCell> append(TAppend tappend) throws IOError, TException {
1788       if (tappend.getRow().length == 0 || tappend.getTable().length == 0) {
1789         throw new TException("Must supply a table and a row key; can't append");
1790       }
1791 
1792       Table table = null;
1793       try {
1794         table = getTable(tappend.getTable());
1795         Append append = ThriftUtilities.appendFromThrift(tappend);
1796         Result result = table.append(append);
1797         return ThriftUtilities.cellFromHBase(result.rawCells());
1798       } catch (IOException e) {
1799         LOG.warn(e.getMessage(), e);
1800         throw new IOError(Throwables.getStackTraceAsString(e));
1801       } finally{
1802           closeTable(table);
1803       }
1804     }
1805 
1806     @Override
1807     public boolean checkAndPut(ByteBuffer tableName, ByteBuffer row, ByteBuffer column,
1808         ByteBuffer value, Mutation mput, Map<ByteBuffer, ByteBuffer> attributes) throws IOError,
1809         IllegalArgument, TException {
1810       Put put;
1811       try {
1812         put = new Put(getBytes(row), HConstants.LATEST_TIMESTAMP);
1813         addAttributes(put, attributes);
1814 
1815         byte[][] famAndQf = KeyValue.parseColumn(getBytes(mput.column));
1816 
1817         put.addImmutable(famAndQf[0], famAndQf[1], mput.value != null ? getBytes(mput.value)
1818             : HConstants.EMPTY_BYTE_ARRAY);
1819 
1820         put.setDurability(mput.writeToWAL ? Durability.SYNC_WAL : Durability.SKIP_WAL);
1821       } catch (IllegalArgumentException e) {
1822         LOG.warn(e.getMessage(), e);
1823         throw new IllegalArgument(Throwables.getStackTraceAsString(e));
1824       }
1825 
1826       Table table = null;
1827       try {
1828         table = getTable(tableName);
1829         byte[][] famAndQf = KeyValue.parseColumn(getBytes(column));
1830         return table.checkAndPut(getBytes(row), famAndQf[0], famAndQf[1],
1831           value != null ? getBytes(value) : HConstants.EMPTY_BYTE_ARRAY, put);
1832       } catch (IOException e) {
1833         LOG.warn(e.getMessage(), e);
1834         throw new IOError(Throwables.getStackTraceAsString(e));
1835       } catch (IllegalArgumentException e) {
1836         LOG.warn(e.getMessage(), e);
1837         throw new IllegalArgument(Throwables.getStackTraceAsString(e));
1838       } finally {
1839           closeTable(table);
1840       }
1841     }
1842   }
1843 
1844 
1845 
1846   /**
1847    * Adds all the attributes into the Operation object
1848    */
1849   private static void addAttributes(OperationWithAttributes op,
1850     Map<ByteBuffer, ByteBuffer> attributes) {
1851     if (attributes == null || attributes.size() == 0) {
1852       return;
1853     }
1854     for (Map.Entry<ByteBuffer, ByteBuffer> entry : attributes.entrySet()) {
1855       String name = Bytes.toStringBinary(getBytes(entry.getKey()));
1856       byte[] value =  getBytes(entry.getValue());
1857       op.setAttribute(name, value);
1858     }
1859   }
1860 
1861   public static void registerFilters(Configuration conf) {
1862     String[] filters = conf.getStrings("hbase.thrift.filters");
1863     if(filters != null) {
1864       for(String filterClass: filters) {
1865         String[] filterPart = filterClass.split(":");
1866         if(filterPart.length != 2) {
1867           LOG.warn("Invalid filter specification " + filterClass + " - skipping");
1868         } else {
1869           ParseFilter.registerFilter(filterPart[0], filterPart[1]);
1870         }
1871       }
1872     }
1873   }
1874 }