1. 程式人生 > >java程式中獲取kerberos登陸hadoop

java程式中獲取kerberos登陸hadoop

本文由作者周樑偉授權網易雲社群釋出。


一般我們在使用kbs登陸hadoop服務時都直接在shell中呼叫kinit命令來獲取憑證,這種方式簡單直接,只要獲取一次憑證之後都可以在該會話過程中重複訪問。但是這種方式一個明顯的問題就是如果在本次shell中會間隔呼叫不同的java程式,而這些程式需要訪問不同許可權的問題,需要在訪問前呼叫各自的ktab檔案獲得授權。這中場景下情況會變得非常複雜,這時如果把kbs認證的過程移到java程式中就會簡單很多,每個java程式中獲取各自的憑證,及時多個程序同時執行也不會產生相互影響。我這裡介紹兩種java中獲取kbs憑證的方法,分別使用 org.apache.hadoop.security.SecurityUtil 和 org.apache.hadoop.security.UserGroupInformation 兩個類實現。

一、    使用ktab檔案簡單登入方式

登入操作函式

/**

      * 嘗試使用kerberos認證登入hfs

      *@params

      *       conf: 配置,其中帶有keytab相關配置屬性

      *       keytab_KEY: 表示conf中代表keytab檔案屬性的鍵值

      *       principal_KEY: 表示conf中代表principal屬性的鍵值

      * @throws IOException

      */

     static void tryKerberosLogin(Configuration conf, String keytab_KEY, String principal_KEY) throws IOException {

          boolean useSec = true;

          LOG.info("Hadoop Security enabled: " + useSec);

          if (!useSec) {

               return;

          }

          try {

               @SuppressWarnings("rawtypes")

               Class c = Class.forName("org.apache.hadoop.security.SecurityUtil");

               // get method login(Configuration, String, String);

               @SuppressWarnings("unchecked")

               Method m = c.getMethod("login", Configuration.class, String.class,

                         String.class);

               m.invoke(null, conf,  keytab_KEY, principal_KEY);

               LOG.info("successfully authenticated with keytab");

          } catch (Exception e) {

               LOG.error(

                         "Flume failed when attempting to authenticate with keytab "

                                   + SimpleConfiguration.get().getKerberosKeytab()

                                   + " and principal '"

                                   + SimpleConfiguration.get().getKerberosPrincipal()

                                   + "'", e);

               return;

          }

     }

配置

...

 <property>

    <name>flume.security.kerberos.principal</name>

    <description></description>

</property>

<property>

    <name>flume.security.kerberos.keytab</name>

    <value>resources/flume.keytab</value>

    <description></description>

</property>

Sample

//呼叫例子

public  FileSystem getFileSystem(Configuration conf) {

               String KEYFILE_key = "flume.security.kerberos.keytab";

               String PRINCIPAL_key = "flume.security.kerberos.principal";

 

               try {

                    // 嘗試用kerberos登入

                    tryKerberosLogin(conf, KEYFILE_key, PRINCIPAL_key);

                    // 獲取一個hdfs例項

                    instance = FileSystem.get( conf);

               } catch (IOException e) {

                    LOG.error("try getFileSystem fail()", e);

               } catch (URISyntaxException e) {

                    LOG.error("try getFileSystem fail()", e);

               }

          }

          return instance;

     }

二、    通過UserGroupInformation獲取代理使用者方式

  package com.netease.backend.bigdata.wa.jobs;

 

import java.io.IOException;

 

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.fs.Path;

import org.apache.hadoop.security.UserGroupInformation;

import org.apache.log4j.Logger;

import org.hsqldb.lib.StringUtil;

 

import com.netease.backend.bigdata.wa.core.ConfKeys;

 

/**

 * 代理使用者資訊認證工具

 *

 * @author zhouliangwei

 *

 */

public class ProxyUGI {

 

     private static Logger LOG = Logger.getLogger(ProxyUGI.class);

 

     private static UserGroupInformation instance = null;

     /**

      * 從Configuration中獲取代理使用者的相關配置,並獲取UserGroupInformation

      * @return

      * @throws IOException

      */

     public synchronized static UserGroupInformation getProxyUGI(Configuration conf) {

          if (instance != null)

               return instance;

          try {

               String username = conf.get(ConfKeys.MR_USER_NAME, "");

               String proxyPrincipal = conf.get(ConfKeys.WDA_PROXY_PRINCIPAL, "");

               String proxyKtab = conf.get(ConfKeys.WDA_PROXY_KEYTAB, "");

               if (StringUtil.isEmpty(username)

                         || StringUtil.isEmpty(proxyPrincipal)

                         || StringUtil.isEmpty(proxyKtab)) {

                    LOG.warn("config properties: ["

                              + ConfKeys.MR_USER_NAME

                              + ", "

                              + ConfKeys.WDA_PROXY_PRINCIPAL

                              + ", "

                              + ConfKeys.WDA_PROXY_KEYTAB

                              + "] in config file './conf/wda-core.xml' must be set!, quite use proxy mechanism");

                    return null;

               }

               instance = UserGroupInformation.createProxyUser(username,

                         UserGroupInformation.loginUserFromKeytabAndReturnUGI(

                                   proxyPrincipal, proxyKtab));

          } catch (IOException ex) {

               //just ignore;

          }

          return instance;

     }

}

呼叫方式

...

public static void main(final String[] args) throws Exception {

          UserGroupInformation ugi = ProxyUGI.getProxyUGI();

          if (ugi != null) {

               ugi.doAs(new PrivilegedExceptionAction<EventJobClient>() {

                    public EventJobClient run() throws Exception {

                         EventJobClient mr = new EventJobClient();

                         int code = ToolRunner.run(mr, args);

                         System.exit(code);

                         return mr;

                    }

               });

               System.exit(1);

          } else {

               int exitCode = ToolRunner.run(new EventJobClient(), args);

               System.exit(exitCode);

          }

     }

….


相關文章:
【推薦】 質量報告之我見