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