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.SecurityUtil;
57  import org.apache.hadoop.hbase.security.UserProvider;
58  import org.apache.hadoop.hbase.thrift.CallQueue;
59  import org.apache.hadoop.hbase.thrift.CallQueue.Call;
60  import org.apache.hadoop.hbase.thrift.ThriftMetrics;
61  import org.apache.hadoop.hbase.thrift2.generated.THBaseService;
62  import org.apache.hadoop.hbase.util.Strings;
63  import org.apache.hadoop.net.DNS;
64  import org.apache.hadoop.security.UserGroupInformation;
65  import org.apache.hadoop.security.SaslRpcServer.SaslGssCallbackHandler;
66  import org.apache.hadoop.util.GenericOptionsParser;
67  import org.apache.thrift.TException;
68  import org.apache.thrift.TProcessor;
69  import org.apache.thrift.protocol.TBinaryProtocol;
70  import org.apache.thrift.protocol.TCompactProtocol;
71  import org.apache.thrift.protocol.TProtocol;
72  import org.apache.thrift.protocol.TProtocolFactory;
73  import org.apache.thrift.server.THsHaServer;
74  import org.apache.thrift.server.TNonblockingServer;
75  import org.apache.thrift.server.TServer;
76  import org.apache.thrift.server.TThreadPoolServer;
77  import org.apache.thrift.transport.TFramedTransport;
78  import org.apache.thrift.transport.TNonblockingServerSocket;
79  import org.apache.thrift.transport.TNonblockingServerTransport;
80  import org.apache.thrift.transport.TSaslServerTransport;
81  import org.apache.thrift.transport.TServerSocket;
82  import org.apache.thrift.transport.TServerTransport;
83  import org.apache.thrift.transport.TTransportException;
84  import org.apache.thrift.transport.TTransportFactory;
85  
86  import com.google.common.util.concurrent.ThreadFactoryBuilder;
87  
88  /**
89   * ThriftServer - this class starts up a Thrift server which implements the HBase API specified in the
90   * HbaseClient.thrift IDL file.
91   */
92  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.TOOLS)
93  @SuppressWarnings({ "rawtypes", "unchecked" })
94  public class ThriftServer {
95    private static final Log log = LogFactory.getLog(ThriftServer.class);
96  
97    /**
98     * Thrift quality of protection configuration key. Valid values can be:
99     * auth-conf: authentication, integrity and confidentiality checking
100    * auth-int: authentication and integrity checking
101    * auth: authentication only
102    *
103    * This is used to authenticate the callers and support impersonation.
104    * The thrift server and the HBase cluster must run in secure mode.
105    */
106   static final String THRIFT_QOP_KEY = "hbase.thrift.security.qop";
107 
108   public static final int DEFAULT_LISTEN_PORT = 9090;
109 
110 
111   public ThriftServer() {
112   }
113 
114   private static void printUsage() {
115     HelpFormatter formatter = new HelpFormatter();
116     formatter.printHelp("Thrift", null, getOptions(),
117         "To start the Thrift server run 'bin/hbase-daemon.sh start thrift2'\n" +
118             "To shutdown the thrift server run 'bin/hbase-daemon.sh stop thrift2' or" +
119             " send a kill signal to the thrift server pid",
120         true);
121   }
122 
123   private static Options getOptions() {
124     Options options = new Options();
125     options.addOption("b", "bind", true,
126         "Address to bind the Thrift server to. [default: 0.0.0.0]");
127     options.addOption("p", "port", true, "Port to bind to [default: " + DEFAULT_LISTEN_PORT + "]");
128     options.addOption("f", "framed", false, "Use framed transport");
129     options.addOption("c", "compact", false, "Use the compact protocol");
130     options.addOption("h", "help", false, "Print help information");
131     options.addOption(null, "infoport", true, "Port for web UI");
132 
133     OptionGroup servers = new OptionGroup();
134     servers.addOption(
135         new Option("nonblocking", false, "Use the TNonblockingServer. This implies the framed transport."));
136     servers.addOption(new Option("hsha", false, "Use the THsHaServer. This implies the framed transport."));
137     servers.addOption(new Option("threadpool", false, "Use the TThreadPoolServer. This is the default."));
138     options.addOptionGroup(servers);
139     return options;
140   }
141 
142   private static CommandLine parseArguments(Configuration conf, Options options, String[] args)
143       throws ParseException, IOException {
144     GenericOptionsParser genParser = new GenericOptionsParser(conf, args);
145     String[] remainingArgs = genParser.getRemainingArgs();
146     CommandLineParser parser = new PosixParser();
147     return parser.parse(options, remainingArgs);
148   }
149 
150   private static TProtocolFactory getTProtocolFactory(boolean isCompact) {
151     if (isCompact) {
152       log.debug("Using compact protocol");
153       return new TCompactProtocol.Factory();
154     } else {
155       log.debug("Using binary protocol");
156       return new TBinaryProtocol.Factory();
157     }
158   }
159 
160   private static TTransportFactory getTTransportFactory(
161       String qop, String name, String host, boolean framed, int frameSize) {
162     if (framed) {
163       if (qop != null) {
164         throw new RuntimeException("Thrift server authentication"
165           + " doesn't work with framed transport yet");
166       }
167       log.debug("Using framed transport");
168       return new TFramedTransport.Factory(frameSize);
169     } else if (qop == null) {
170       return new TTransportFactory();
171     } else {
172       Map<String, String> saslProperties = new HashMap<String, String>();
173       saslProperties.put(Sasl.QOP, qop);
174       TSaslServerTransport.Factory saslFactory = new TSaslServerTransport.Factory();
175       saslFactory.addServerDefinition("GSSAPI", name, host, saslProperties,
176         new SaslGssCallbackHandler() {
177           @Override
178           public void handle(Callback[] callbacks)
179               throws UnsupportedCallbackException {
180             AuthorizeCallback ac = null;
181             for (Callback callback : callbacks) {
182               if (callback instanceof AuthorizeCallback) {
183                 ac = (AuthorizeCallback) callback;
184               } else {
185                 throw new UnsupportedCallbackException(callback,
186                     "Unrecognized SASL GSSAPI Callback");
187               }
188             }
189             if (ac != null) {
190               String authid = ac.getAuthenticationID();
191               String authzid = ac.getAuthorizationID();
192               if (!authid.equals(authzid)) {
193                 ac.setAuthorized(false);
194               } else {
195                 ac.setAuthorized(true);
196                 String userName = SecurityUtil.getUserFromPrincipal(authzid);
197                 log.info("Effective user: " + userName);
198                 ac.setAuthorizedID(userName);
199               }
200             }
201           }
202         });
203       return saslFactory;
204     }
205   }
206 
207   /*
208    * If bindValue is null, we don't bind.
209    */
210   private static InetSocketAddress bindToPort(String bindValue, int listenPort)
211       throws UnknownHostException {
212     try {
213       if (bindValue == null) {
214         return new InetSocketAddress(listenPort);
215       } else {
216         return new InetSocketAddress(InetAddress.getByName(bindValue), listenPort);
217       }
218     } catch (UnknownHostException e) {
219       throw new RuntimeException("Could not bind to provided ip address", e);
220     }
221   }
222 
223   private static TServer getTNonBlockingServer(TProtocolFactory protocolFactory, TProcessor processor,
224       TTransportFactory transportFactory, InetSocketAddress inetSocketAddress) throws TTransportException {
225     TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
226     log.info("starting HBase Nonblocking Thrift server on " + inetSocketAddress.toString());
227     TNonblockingServer.Args serverArgs = new TNonblockingServer.Args(serverTransport);
228     serverArgs.processor(processor);
229     serverArgs.transportFactory(transportFactory);
230     serverArgs.protocolFactory(protocolFactory);
231     return new TNonblockingServer(serverArgs);
232   }
233 
234   private static TServer getTHsHaServer(TProtocolFactory protocolFactory,
235       TProcessor processor, TTransportFactory transportFactory,
236       InetSocketAddress inetSocketAddress, ThriftMetrics metrics)
237       throws TTransportException {
238     TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(inetSocketAddress);
239     log.info("starting HBase HsHA Thrift server on " + inetSocketAddress.toString());
240     THsHaServer.Args serverArgs = new THsHaServer.Args(serverTransport);
241     ExecutorService executorService = createExecutor(
242         serverArgs.getWorkerThreads(), metrics);
243     serverArgs.executorService(executorService);
244     serverArgs.processor(processor);
245     serverArgs.transportFactory(transportFactory);
246     serverArgs.protocolFactory(protocolFactory);
247     return new THsHaServer(serverArgs);
248   }
249 
250   private static ExecutorService createExecutor(
251       int workerThreads, ThriftMetrics metrics) {
252     CallQueue callQueue = new CallQueue(
253         new LinkedBlockingQueue<Call>(), metrics);
254     ThreadFactoryBuilder tfb = new ThreadFactoryBuilder();
255     tfb.setDaemon(true);
256     tfb.setNameFormat("thrift2-worker-%d");
257     return new ThreadPoolExecutor(workerThreads, workerThreads,
258             Long.MAX_VALUE, TimeUnit.SECONDS, callQueue, tfb.build());
259   }
260 
261   private static TServer getTThreadPoolServer(TProtocolFactory protocolFactory, TProcessor processor,
262       TTransportFactory transportFactory, InetSocketAddress inetSocketAddress) throws TTransportException {
263     TServerTransport serverTransport = new TServerSocket(inetSocketAddress);
264     log.info("starting HBase ThreadPool Thrift server on " + inetSocketAddress.toString());
265     TThreadPoolServer.Args serverArgs = new TThreadPoolServer.Args(serverTransport);
266     serverArgs.processor(processor);
267     serverArgs.transportFactory(transportFactory);
268     serverArgs.protocolFactory(protocolFactory);
269     return new TThreadPoolServer(serverArgs);
270   }
271 
272   /**
273    * Adds the option to pre-load filters at startup.
274    *
275    * @param conf  The current configuration instance.
276    */
277   protected static void registerFilters(Configuration conf) {
278     String[] filters = conf.getStrings("hbase.thrift.filters");
279     if(filters != null) {
280       for(String filterClass: filters) {
281         String[] filterPart = filterClass.split(":");
282         if(filterPart.length != 2) {
283           log.warn("Invalid filter specification " + filterClass + " - skipping");
284         } else {
285           ParseFilter.registerFilter(filterPart[0], filterPart[1]);
286         }
287       }
288     }
289   }
290 
291   /**
292    * Start up the Thrift2 server.
293    *
294    * @param args
295    */
296   public static void main(String[] args) throws Exception {
297     TServer server = null;
298     Options options = getOptions();
299     Configuration conf = HBaseConfiguration.create();
300     CommandLine cmd = parseArguments(conf, options, args);
301 
302     /**
303      * This is to please both bin/hbase and bin/hbase-daemon. hbase-daemon provides "start" and "stop" arguments hbase
304      * should print the help if no argument is provided
305      */
306     List<?> argList = cmd.getArgList();
307     if (cmd.hasOption("help") || !argList.contains("start") || argList.contains("stop")) {
308       printUsage();
309       System.exit(1);
310     }
311 
312     // Get port to bind to
313     int listenPort = 0;
314     try {
315       if (cmd.hasOption("port")) {
316         listenPort = Integer.parseInt(cmd.getOptionValue("port"));
317       } else {
318         listenPort = conf.getInt("hbase.regionserver.thrift.port", DEFAULT_LISTEN_PORT);
319       }
320     } catch (NumberFormatException e) {
321       throw new RuntimeException("Could not parse the value provided for the port option", e);
322     }
323 
324     // Local hostname and user name,
325     // used only if QOP is configured.
326     String host = null;
327     String name = null;
328 
329     UserProvider userProvider = UserProvider.instantiate(conf);
330     // login the server principal (if using secure Hadoop)
331     boolean securityEnabled = userProvider.isHadoopSecurityEnabled()
332       && userProvider.isHBaseSecurityEnabled();
333     if (securityEnabled) {
334       host = Strings.domainNamePointerToHostName(DNS.getDefaultHost(
335         conf.get("hbase.thrift.dns.interface", "default"),
336         conf.get("hbase.thrift.dns.nameserver", "default")));
337       userProvider.login("hbase.thrift.keytab.file",
338         "hbase.thrift.kerberos.principal", host);
339     }
340 
341     UserGroupInformation realUser = userProvider.getCurrent().getUGI();
342     String qop = conf.get(THRIFT_QOP_KEY);
343     if (qop != null) {
344       if (!qop.equals("auth") && !qop.equals("auth-int")
345           && !qop.equals("auth-conf")) {
346         throw new IOException("Invalid " + THRIFT_QOP_KEY + ": " + qop
347           + ", it must be 'auth', 'auth-int', or 'auth-conf'");
348       }
349       if (!securityEnabled) {
350         throw new IOException("Thrift server must"
351           + " run in secure mode to support authentication");
352       }
353       // Extract the name from the principal
354       name = SecurityUtil.getUserFromPrincipal(
355         conf.get("hbase.thrift.kerberos.principal"));
356     }
357 
358     boolean nonblocking = cmd.hasOption("nonblocking");
359     boolean hsha = cmd.hasOption("hsha");
360 
361     ThriftMetrics metrics = new ThriftMetrics(conf, ThriftMetrics.ThriftServerType.TWO);
362 
363     String implType = "threadpool";
364     if (nonblocking) {
365       implType = "nonblocking";
366     } else if (hsha) {
367       implType = "hsha";
368     }
369 
370     conf.set("hbase.regionserver.thrift.server.type", implType);
371     conf.setInt("hbase.regionserver.thrift.port", listenPort);
372     registerFilters(conf);
373 
374     // Construct correct ProtocolFactory
375     boolean compact = cmd.hasOption("compact") ||
376         conf.getBoolean("hbase.regionserver.thrift.compact", false);
377     TProtocolFactory protocolFactory = getTProtocolFactory(compact);
378     final ThriftHBaseServiceHandler hbaseHandler =
379       new ThriftHBaseServiceHandler(conf, userProvider);
380     THBaseService.Iface handler =
381       ThriftHBaseServiceHandler.newInstance(hbaseHandler, metrics);
382     final THBaseService.Processor p = new THBaseService.Processor(handler);
383     conf.setBoolean("hbase.regionserver.thrift.compact", compact);
384     TProcessor processor = p;
385 
386     boolean framed = cmd.hasOption("framed") ||
387         conf.getBoolean("hbase.regionserver.thrift.framed", false) || nonblocking || hsha;
388     TTransportFactory transportFactory = getTTransportFactory(qop, name, host, framed,
389         conf.getInt("hbase.regionserver.thrift.framed.max_frame_size_in_mb", 2) * 1024 * 1024);
390     InetSocketAddress inetSocketAddress = bindToPort(cmd.getOptionValue("bind"), listenPort);
391     conf.setBoolean("hbase.regionserver.thrift.framed", framed);
392     if (qop != null) {
393       // Create a processor wrapper, to get the caller
394       processor = new TProcessor() {
395         @Override
396         public boolean process(TProtocol inProt,
397             TProtocol outProt) throws TException {
398           TSaslServerTransport saslServerTransport =
399             (TSaslServerTransport)inProt.getTransport();
400           SaslServer saslServer = saslServerTransport.getSaslServer();
401           String principal = saslServer.getAuthorizationID();
402           hbaseHandler.setEffectiveUser(principal);
403           return p.process(inProt, outProt);
404         }
405       };
406     }
407 
408     // check for user-defined info server port setting, if so override the conf
409     try {
410       if (cmd.hasOption("infoport")) {
411         String val = cmd.getOptionValue("infoport");
412         conf.setInt("hbase.thrift.info.port", Integer.valueOf(val));
413         log.debug("Web UI port set to " + val);
414       }
415     } catch (NumberFormatException e) {
416       log.error("Could not parse the value provided for the infoport option", e);
417       printUsage();
418       System.exit(1);
419     }
420 
421     // Put up info server.
422     int port = conf.getInt("hbase.thrift.info.port", 9095);
423     if (port >= 0) {
424       conf.setLong("startcode", System.currentTimeMillis());
425       String a = conf.get("hbase.thrift.info.bindAddress", "0.0.0.0");
426       InfoServer infoServer = new InfoServer("thrift", a, port, false, conf);
427       infoServer.setAttribute("hbase.conf", conf);
428       infoServer.start();
429     }
430 
431     if (nonblocking) {
432       server = getTNonBlockingServer(protocolFactory, processor, transportFactory, inetSocketAddress);
433     } else if (hsha) {
434       server = getTHsHaServer(protocolFactory, processor, transportFactory, inetSocketAddress, metrics);
435     } else {
436       server = getTThreadPoolServer(protocolFactory, processor, transportFactory, inetSocketAddress);
437     }
438 
439     final TServer tserver = server;
440     realUser.doAs(
441       new PrivilegedAction<Object>() {
442         @Override
443         public Object run() {
444           tserver.serve();
445           return null;
446         }
447       });
448   }
449 }