View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.thrift2;
20  
21  import java.io.IOException;
22  import java.net.InetAddress;
23  import java.net.InetSocketAddress;
24  import java.net.UnknownHostException;
25  import java.security.PrivilegedAction;
26  import java.util.HashMap;
27  import java.util.List;
28  import java.util.Map;
29  import java.util.concurrent.ExecutorService;
30  import java.util.concurrent.LinkedBlockingQueue;
31  import java.util.concurrent.ThreadPoolExecutor;
32  import java.util.concurrent.TimeUnit;
33  
34  import javax.security.auth.callback.Callback;
35  import javax.security.auth.callback.UnsupportedCallbackException;
36  import javax.security.sasl.AuthorizeCallback;
37  import javax.security.sasl.Sasl;
38  import javax.security.sasl.SaslServer;
39  
40  import org.apache.commons.cli.CommandLine;
41  import org.apache.commons.cli.CommandLineParser;
42  import org.apache.commons.cli.HelpFormatter;
43  import org.apache.commons.cli.Option;
44  import org.apache.commons.cli.OptionGroup;
45  import org.apache.commons.cli.Options;
46  import org.apache.commons.cli.ParseException;
47  import org.apache.commons.cli.PosixParser;
48  import org.apache.commons.logging.Log;
49  import org.apache.commons.logging.LogFactory;
50  import org.apache.hadoop.hbase.classification.InterfaceAudience;
51  import org.apache.hadoop.conf.Configuration;
52  import org.apache.hadoop.hbase.HBaseConfiguration;
53  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
54  import org.apache.hadoop.hbase.filter.ParseFilter;
55  import org.apache.hadoop.hbase.http.InfoServer;
56  import org.apache.hadoop.hbase.security.SaslUtil;
57  import org.apache.hadoop.hbase.security.SecurityUtil;
58  import org.apache.hadoop.hbase.security.UserProvider;
59  import org.apache.hadoop.hbase.thrift.CallQueue;
60  import org.apache.hadoop.hbase.thrift.CallQueue.Call;
61  import org.apache.hadoop.hbase.thrift.ThriftMetrics;
62  import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
63  import org.apache.hadoop.hbase.util.DNS;
64  import org.apache.hadoop.hbase.util.Strings;
65  import org.apache.hadoop.security.UserGroupInformation;
66  import org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler;
67  import org.apache.hadoop.util.GenericOptionsParser;
68  import org.apache.thrift.TException;
69  import org.apache.thrift.TProcessor;
70  import org.apache.thrift.protocol.TBinaryProtocol;
71  import org.apache.thrift.protocol.TCompactProtocol;
72  import org.apache.thrift.protocol.TProtocol;
73  import org.apache.thrift.protocol.TProtocolFactory;
74  import org.apache.thrift.server.THsHaServer;
75  import org.apache.thrift.server.TNonblockingServer;
76  import org.apache.thrift.server.TServer;
77  import org.apache.thrift.server.TThreadPoolServer;
78  import org.apache.thrift.server.TThreadedSelectorServer;
79  import org.apache.thrift.transport.TFramedTransport;
80  import org.apache.thrift.transport.TNonblockingServerSocket;
81  import org.apache.thrift.transport.TNonblockingServerTransport;
82  import org.apache.thrift.transport.TSaslServerTransport;
83  import org.apache.thrift.transport.TServerSocket;
84  import org.apache.thrift.transport.TServerTransport;
85  import org.apache.thrift.transport.TTransportException;
86  import org.apache.thrift.transport.TTransportFactory;
87  
88  import com.google.common.util.concurrent.ThreadFactoryBuilder;
89  
90  /**
91   * ThriftServer - this class starts up a Thrift server which implements the HBase API specified in the
92   * HbaseClient.thrift IDL file.
93   */
94  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
95  @SuppressWarnings({ "rawtypes", "unchecked" })
96  public class ThriftServer {
97    private static final Log log = LogFactory.getLog(ThriftServer.class);
98  
99    /**
100    * Thrift quality of protection configuration key. Valid values can be:
101    * privacy: authentication, integrity and confidentiality checking
102    * integrity: authentication and integrity checking
103    * authentication: authentication only
104    *
105    * This is used to authenticate the callers and support impersonation.
106    * The thrift server and the HBase cluster must run in secure mode.
107    */
108   static final String THRIFT_QOP_KEY = "hbase.thrift.security.qop";
109 
110   public static final int DEFAULT_LISTEN_PORT = 9090;
111 
112   private static final String READ_TIMEOUT_OPTION = "readTimeout";
113 
114   static final String BACKLOG_CONF_KEY = "hbase.regionserver.thrift.backlog";
115 
116   /**
117    * Amount of time in milliseconds before a server thread will timeout
118    * waiting for client to send data on a connected socket. Currently,
119    * applies only to TBoundedThreadPoolServer
120    */
121   public static final String THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY =
122     "hbase.thrift.server.socket.read.timeout";
123   public static final int THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT = 60000;
124 
125   public ThriftServer() {
126   }
127 
128   private static void printUsage() {
129     HelpFormatter formatter = new HelpFormatter();
130     formatter.printHelp("Thrift", null, getOptions(),
131         "To start the Thrift server run 'bin/hbase-daemon.sh start thrift2'\n" +
132             "To shutdown the thrift server run 'bin/hbase-daemon.sh stop thrift2' or" +
133             " send a kill signal to the thrift server pid",
134         true);
135   }
136 
137   private static Options getOptions() {
138     Options options = new Options();
139     options.addOption("b", "bind", true,
140         "Address to bind the Thrift server to. [default: 0.0.0.0]");
141     options.addOption("p", "port", true, "Port to bind to [default: " + DEFAULT_LISTEN_PORT + "]");
142     options.addOption("f", "framed", false, "Use framed transport");
143     options.addOption("c", "compact", false, "Use the compact protocol");
144     options.addOption("w", "workers", true, "How many worker threads to use.");
145     options.addOption("s", "selectors", true, "How many selector threads to use.");
146     options.addOption("h", "help", false, "Print help information");
147     options.addOption(null, "infoport", true, "Port for web UI");
148     options.addOption("t", READ_TIMEOUT_OPTION, true,
149       "Amount of time in milliseconds before a server thread will timeout " +
150       "waiting for client to send data on a connected socket. Currently, " +
151       "only applies to TBoundedThreadPoolServer");
152     OptionGroup servers = new OptionGroup();
153     servers.addOption(
154         new Option("nonblocking", false, "Use the TNonblockingServer. This implies the framed transport."));
155     servers.addOption(new Option("hsha", false, "Use the THsHaServer. This implies the framed transport."));
156     servers.addOption(new Option("selector", false, "Use the TThreadedSelectorServer. This implies the framed transport."));
157     servers.addOption(new Option("threadpool", false, "Use the TThreadPoolServer. This is the default."));
158     options.addOptionGroup(servers);
159     return options;
160   }
161 
162   private static CommandLine parseArguments(Configuration conf, Options options, String[] args)
163       throws ParseException, IOException {
164     GenericOptionsParser genParser = new GenericOptionsParser(conf, args);
165     String[] remainingArgs = genParser.getRemainingArgs();
166     CommandLineParser parser = new PosixParser();
167     return parser.parse(options, remainingArgs);
168   }
169 
170   private static TProtocolFactory getTProtocolFactory(boolean isCompact) {
171     if (isCompact) {
172       log.debug("Using compact protocol");
173       return new TCompactProtocol.Factory();
174     } else {
175       log.debug("Using binary protocol");
176       return new TBinaryProtocol.Factory();
177     }
178   }
179 
180   private static TTransportFactory getTTransportFactory(
181       SaslUtil.QualityOfProtection qop, String name, String host,
182       boolean framed, int frameSize) {
183     if (framed) {
184       if (qop != null) {
185         throw new RuntimeException("Thrift server authentication"
186           + " doesn't work with framed transport yet");
187       }
188       log.debug("Using framed transport");
189       return new TFramedTransport.Factory(frameSize);
190     } else if (qop == null) {
191       return new TTransportFactory();
192     } else {
193       Map<String, String> saslProperties = new HashMap<String, String>();
194       saslProperties.put(Sasl.QOP, qop.getSaslQop());
195       TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
196       saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties,
197         new SaslGssCallbackHandler() {
198           @Override
199           public void handle(Callback[] callbacks)
200               throws UnsupportedCallbackException {
201             AuthorizeCallback ac = null;
202             for (Callback callback : callbacks) {
203               if (callback instanceof AuthorizeCallback) {
204                 ac = (AuthorizeCallback) callback;
205               } else {
206                 throw new UnsupportedCallbackException(callback,
207                     "Unrecognized SASL GSSAPI Callback");
208               }
209             }
210             if (ac != null) {
211               String authid = ac.getAuthenticationID();
212               String authzid = ac.getAuthorizationID();
213               if (!authid.equals(authzid)) {
214                 ac.setAuthorized(false);
215               } else {
216                 ac.setAuthorized(true);
217                 String userName = SecurityUtil.getUserFromPrincipal(authzid);
218                 log.info("Effective user: " + userName);
219                 ac.setAuthorizedID(userName);
220               }
221             }
222           }
223         });
224       return saslFactory;
225     }
226   }
227 
228   /*
229    * If bindValue is null, we don't bind.
230    */
231   private static InetSocketAddress bindToPort(String bindValue, int listenPort)
232       throws UnknownHostException {
233     try {
234       if (bindValue == null) {
235         return new InetSocketAddress(listenPort);
236       } else {
237         return new InetSocketAddress(InetAddress.getByName(bindValue), listenPort);
238       }
239     } catch (UnknownHostException e) {
240       throw new RuntimeException("Could not bind to provided ip address", e);
241     }
242   }
243 
244   private static TServer getTNonBlockingServer(TProtocolFactory protocolFactory, TProcessor processor,
245       TTransportFactory transportFactory, InetSocketAddress inetSocketAddress) throws TTransportException {
246     TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
247     log.info("starting HBase Nonblocking Thrift server on " + inetSocketAddress.toString());
248     TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);
249     serverArgs.processor(processor);
250     serverArgs.transportFactory(transportFactory);
251     serverArgs.protocolFactory(protocolFactory);
252     return new TNonblockingServer(serverArgs);
253   }
254 
255   private static TServer getTHsHaServer(TProtocolFactory protocolFactory,
256       TProcessor processor, TTransportFactory transportFactory,
257       int workerThreads,
258       InetSocketAddress inetSocketAddress, ThriftMetrics metrics)
259       throws TTransportException {
260     TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
261     log.info("starting HBase HsHA Thrift server on " + inetSocketAddress.toString());
262     THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
263     if (workerThreads > 0) {
264       // Could support the min & max threads, avoiding to preserve existing functionality.
265       serverArgs.minWorkerThreads(workerThreads).maxWorkerThreads(workerThreads);
266     }
267     ExecutorService executorService = createExecutor(
268         workerThreads, metrics);
269     serverArgs.executorService(executorService);
270     serverArgs.processor(processor);
271     serverArgs.transportFactory(transportFactory);
272     serverArgs.protocolFactory(protocolFactory);
273     return new THsHaServer(serverArgs);
274   }
275 
276   private static TServer getTThreadedSelectorServer(TProtocolFactory protocolFactory,
277           TProcessor processor, TTransportFactory transportFactory,
278           int workerThreads, int selectorThreads,
279           InetSocketAddress inetSocketAddress, ThriftMetrics metrics)
280           throws TTransportException {
281         TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
282         log.info("starting HBase ThreadedSelector Thrift server on " + inetSocketAddress.toString());
283         TThreadedSelectorServer.Args serverArgs = new TThreadedSelectorServer.Args(serverTransport);
284         if (workerThreads > 0) {
285             serverArgs.workerThreads(workerThreads);
286         }
287         if (selectorThreads > 0) {
288             serverArgs.selectorThreads(selectorThreads);
289         }
290 
291         ExecutorService executorService = createExecutor(
292             workerThreads, metrics);
293         serverArgs.executorService(executorService);
294         serverArgs.processor(processor);
295         serverArgs.transportFactory(transportFactory);
296         serverArgs.protocolFactory(protocolFactory);
297         return new TThreadedSelectorServer(serverArgs);
298       }
299 
300   private static ExecutorService createExecutor(
301       int workerThreads, ThriftMetrics metrics) {
302     CallQueue callQueue = new CallQueue(
303         new LinkedBlockingQueue<Call>(), metrics);
304     ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
305     tfb.setDaemon(true);
306     tfb.setNameFormat("thrift2-worker-%d");
307     ThreadPoolExecutor pool = new ThreadPoolExecutor(workerThreads, workerThreads,
308             Long.MAX_VALUE, TimeUnit.SECONDS, callQueue, tfb.build());
309     pool.prestartAllCoreThreads();
310     return pool;
311   }
312 
313   private static TServer getTThreadPoolServer(TProtocolFactory protocolFactory,
314                                               TProcessor processor,
315                                               TTransportFactory transportFactory,
316                                               int workerThreads,
317                                               InetSocketAddress inetSocketAddress,
318                                               int backlog,
319                                               int clientTimeout)
320       throws TTransportException {
321     TServerTransport serverTransport = new TServerSocket(
322                                            new TServerSocket.ServerSocketTransportArgs().
323                                                bindAddr(inetSocketAddress).backlog(backlog).
324                                                clientTimeout(clientTimeout));
325     log.info("starting HBase ThreadPool Thrift server on " + inetSocketAddress.toString());
326     TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport);
327     serverArgs.processor(processor);
328     serverArgs.transportFactory(transportFactory);
329     serverArgs.protocolFactory(protocolFactory);
330     if (workerThreads > 0) {
331       serverArgs.maxWorkerThreads(workerThreads);
332     }
333     return new TThreadPoolServer(serverArgs);
334   }
335 
336   /**
337    * Adds the option to pre-load filters at startup.
338    *
339    * @param conf  The current configuration instance.
340    */
341   protected static void registerFilters(Configuration conf) {
342     String[] filters = conf.getStrings("hbase.thrift.filters");
343     if(filters != null) {
344       for(String filterClass: filters) {
345         String[] filterPart = filterClass.split(":");
346         if(filterPart.length != 2) {
347           log.warn("Invalid filter specification " + filterClass + " - skipping");
348         } else {
349           ParseFilter.registerFilter(filterPart[0], filterPart[1]);
350         }
351       }
352     }
353   }
354 
355   /**
356    * Start up the Thrift2 server.
357    *
358    * @param args
359    */
360   public static void main(String[] args) throws Exception {
361     TServer server = null;
362     Options options = getOptions();
363     Configuration conf = HBaseConfiguration.create();
364     CommandLine cmd = parseArguments(conf, options, args);
365     int workerThreads = 0;
366     int selectorThreads = 0;
367 
368     /**
369      * This is to please both bin/hbase and bin/hbase-daemon. hbase-daemon provides "start" and "stop" arguments hbase
370      * should print the help if no argument is provided
371      */
372     List<?> argList = cmd.getArgList();
373     if (cmd.hasOption("help") || !argList.contains("start") || argList.contains("stop")) {
374       printUsage();
375       System.exit(1);
376     }
377 
378     // Get address to bind
379     String bindAddress;
380     if (cmd.hasOption("bind")) {
381       bindAddress = cmd.getOptionValue("bind");
382       conf.set("hbase.thrift.info.bindAddress", bindAddress);
383     } else {
384       bindAddress = conf.get("hbase.thrift.info.bindAddress");
385     }
386 
387     // Get read timeout
388     int readTimeout = THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT;
389     if (cmd.hasOption(READ_TIMEOUT_OPTION)) {
390       try {
391         readTimeout = Integer.parseInt(cmd.getOptionValue(READ_TIMEOUT_OPTION));
392       } catch (NumberFormatException e) {
393         throw new RuntimeException("Could not parse the value provided for the timeout option", e);
394       }
395     } else {
396       readTimeout = conf.getInt(THRIFT_SERVER_SOCKET_READ_TIMEOUT_KEY,
397         THRIFT_SERVER_SOCKET_READ_TIMEOUT_DEFAULT);
398     }
399 
400     // Get port to bind to
401     int listenPort = 0;
402     try {
403       if (cmd.hasOption("port")) {
404         listenPort = Integer.parseInt(cmd.getOptionValue("port"));
405       } else {
406         listenPort = conf.getInt("hbase.regionserver.thrift.port", DEFAULT_LISTEN_PORT);
407       }
408     } catch (NumberFormatException e) {
409       throw new RuntimeException("Could not parse the value provided for the port option", e);
410     }
411 
412     // Thrift's implementation uses '0' as a placeholder for 'use the default.'
413     int backlog = conf.getInt(BACKLOG_CONF_KEY, 0);
414 
415     // Local hostname and user name,
416     // used only if QOP is configured.
417     String host = null;
418     String name = null;
419 
420     UserProvider userProvider = UserProvider.instantiate(conf);
421     // login the server principal (if using secure Hadoop)
422     boolean securityEnabled = userProvider.isHadoopSecurityEnabled()
423       && userProvider.isHBaseSecurityEnabled();
424     if (securityEnabled) {
425       host = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
426         conf.get("hbase.thrift.dns.interface", "default"),
427         conf.get("hbase.thrift.dns.nameserver", "default")));
428       userProvider.login("hbase.thrift.keytab.file",
429         "hbase.thrift.kerberos.principal", host);
430     }
431 
432     UserGroupInformation realUser = userProvider.getCurrent().getUGI();
433     String stringQop = conf.get(THRIFT_QOP_KEY);
434     SaslUtil.QualityOfProtection qop = null;
435     if (stringQop != null) {
436       qop = SaslUtil.getQop(stringQop);
437       if (!securityEnabled) {
438         throw new IOException("Thrift server must"
439           + " run in secure mode to support authentication");
440       }
441       // Extract the name from the principal
442       name = SecurityUtil.getUserFromPrincipal(
443         conf.get("hbase.thrift.kerberos.principal"));
444     }
445 
446     boolean nonblocking = cmd.hasOption("nonblocking");
447     boolean hsha = cmd.hasOption("hsha");
448     boolean selector = cmd.hasOption("selector");
449 
450     ThriftMetrics metrics = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.TWO);
451 
452     String implType = "threadpool";
453     if (nonblocking) {
454       implType = "nonblocking";
455     } else if (hsha) {
456       implType = "hsha";
457     } else if (selector) {
458       implType = "selector";
459     }
460 
461     conf.set("hbase.regionserver.thrift.server.type", implType);
462     conf.setInt("hbase.regionserver.thrift.port", listenPort);
463     registerFilters(conf);
464 
465     // Construct correct ProtocolFactory
466     boolean compact = cmd.hasOption("compact") ||
467         conf.getBoolean("hbase.regionserver.thrift.compact", false);
468     TProtocolFactory protocolFactory = getTProtocolFactory(compact);
469     final ThriftHBaseServiceHandler hbaseHandler =
470       new ThriftHBaseServiceHandler(conf, userProvider);
471     THBaseService.Iface handler =
472       ThriftHBaseServiceHandler.newInstance(hbaseHandler, metrics);
473     final THBaseService.Processor p = new THBaseService.Processor(handler);
474     conf.setBoolean("hbase.regionserver.thrift.compact", compact);
475     TProcessor processor = p;
476 
477     boolean framed = cmd.hasOption("framed") ||
478         conf.getBoolean("hbase.regionserver.thrift.framed", false) || nonblocking || hsha;
479     TTransportFactory transportFactory = getTTransportFactory(qop, name, host, framed,
480         conf.getInt("hbase.regionserver.thrift.framed.max_frame_size_in_mb", 2) * 1024 * 1024);
481     InetSocketAddress inetSocketAddress = bindToPort(bindAddress, listenPort);
482     conf.setBoolean("hbase.regionserver.thrift.framed", framed);
483     if (qop != null) {
484       // Create a processor wrapper, to get the caller
485       processor = new TProcessor() {
486         @Override
487         public boolean process(TProtocol inProt,
488             TProtocol outProt) throws TException {
489           TSaslServerTransport saslServerTransport =
490             (TSaslServerTransport)inProt.getTransport();
491           SaslServer saslServer = saslServerTransport.getSaslServer();
492           String principal = saslServer.getAuthorizationID();
493           hbaseHandler.setEffectiveUser(principal);
494           return p.process(inProt, outProt);
495         }
496       };
497     }
498 
499     if (cmd.hasOption("w")) {
500       workerThreads = Integer.parseInt(cmd.getOptionValue("w"));
501     }
502     if (cmd.hasOption("s")) {
503       selectorThreads = Integer.parseInt(cmd.getOptionValue("s"));
504     }
505 
506     // check for user-defined info server port setting, if so override the conf
507     try {
508       if (cmd.hasOption("infoport")) {
509         String val = cmd.getOptionValue("infoport");
510         conf.setInt("hbase.thrift.info.port", Integer.parseInt(val));
511         log.debug("Web UI port set to " + val);
512       }
513     } catch (NumberFormatException e) {
514       log.error("Could not parse the value provided for the infoport option", e);
515       printUsage();
516       System.exit(1);
517     }
518 
519     // Put up info server.
520     int port = conf.getInt("hbase.thrift.info.port", 9095);
521     if (port >= 0) {
522       conf.setLong("startcode", System.currentTimeMillis());
523       String a = conf.get("hbase.thrift.info.bindAddress", "0.0.0.0");
524       InfoServer infoServer = new InfoServer("thrift", a, port, false, conf);
525       infoServer.setAttribute("hbase.conf", conf);
526       infoServer.start();
527     }
528 
529     if (nonblocking) {
530       server = getTNonBlockingServer(protocolFactory,
531           processor,
532           transportFactory,
533           inetSocketAddress);
534     } else if (hsha) {
535       server = getTHsHaServer(protocolFactory,
536           processor,
537           transportFactory,
538           workerThreads,
539           inetSocketAddress,
540           metrics);
541     } else if (selector) {
542           server = getTThreadedSelectorServer(protocolFactory,
543           processor,
544           transportFactory,
545           workerThreads, selectorThreads,
546           inetSocketAddress,
547           metrics);
548     } else {
549       server = getTThreadPoolServer(protocolFactory,
550           processor,
551           transportFactory,
552           workerThreads,
553           inetSocketAddress,
554           backlog,
555           readTimeout);
556     }
557 
558     final TServer tserver = server;
559     realUser.doAs(
560       new PrivilegedAction<Object>() {
561         @Override
562         public Object run() {
563           tserver.serve();
564           return null;
565         }
566       });
567   }
568 }