Java&Python操作WebHDFS

有用到通过java client或者python client操作HDFS,记录一下简单的代码片段。


WebHDFS的认证方式

WebHDFS的认证方式有三种:

Authentication

When security is off, the authenticated user is the username specified in the user.name query parameter. If the user.name parameter is not set, the server may either set the authenticated user to a default web user, if there is any, or return an error response.

When security is on, authentication is performed by either Hadoop delegation token or Kerberos SPNEGO. If a token is set in the delegation query parameter, the authenticated user is the user encoded in the token. If the delegation parameter is not set, the user is authenticated by Kerberos SPNEGO.

Below are examples using the curl command tool.

Authentication when security is off:

curl -i “http://:/webhdfs/v1/?[user.name=&]op=…”
Authentication using Kerberos SPNEGO when security is on:

curl -i –negotiate -u : “http://:/webhdfs/v1/?op=…”
Authentication using Hadoop delegation token when security is on:

curl -i “http://:/webhdfs/v1/?delegation=&op=…”


Java访问WebHDFS

这里没有开启安全认证。

测试的REST API: http://10.254.100.198:50070/webhdfs/v1/Project?op=LISTSTATUS&user.name=hdfs

代码片段:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

    /**
     * <b>LISTSTATUS</b>
     *
     * curl -i "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=LISTSTATUS&user.name=hdfs"
     *
     * @param totalDir
     * @return
     * @throws IOException
     */
    public List<String> getHDFSDirs(String totalDir, String host, String port) throws IOException {
        String httpfsUrl = BackupUtils.DEFAULT_PROTOCOL + host + ":" + port;
        String spec = MessageFormat.format("/webhdfs/v1{0}?op=LISTSTATUS&user.name={1}", totalDir, "hdfs");
        URL url = new URL(new URL(httpfsUrl), spec);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.connect();
        String resp = result(conn, true);
        conn.disconnect();

        JSONObject root = JSON.parseObject(resp);
        int size = root.getJSONObject("FileStatuses").getJSONArray("FileStatus").size();

        List<String> dirs = new ArrayList<>();
        for(int i = 0; i < size; ++i) {
            String dir = root.getJSONObject("FileStatuses").getJSONArray("FileStatus").getJSONObject(i).getString("pathSuffix");
            dirs.add(dir);
        }
        return dirs;
    }

    /**
     * Report the result in STRING way
     *
     * @param conn
     * @param input
     * @return
     * @throws IOException
     */
    public String result(HttpURLConnection conn, boolean input) throws IOException {
        StringBuffer sb = new StringBuffer();
        if (input) {
            InputStream is = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            reader.close();
            is.close();
        }
        return sb.toString();
    }


Python访问WebHDFS

同样也没有开启安全认证。

测试的REST API: http://10.254.100.198:50070/webhdfs/v1/Project?op=LISTSTATUS&user.name=hdfs

代码片段:

agent_config = AmbariConfig()
WEBHDFS_CONTEXT_ROOT="/webhdfs/v1"

class WebHDFS(object):
    """ Class for accessing HDFS via WebHDFS

        To enable WebHDFS in your Hadoop Installation add the following configuration
        to your hdfs_site.xml (requires Hadoop >0.20.205.0):

        <property>
             <name>dfs.webhdfs.enabled</name>
             <value>true</value>
        </property>

    """

    def __init__(self, namenode_host, namenode_port, hdfs_username):
        self.namenode_host=namenode_host
        self.namenode_port = namenode_port
        self.username = hdfs_username

    def __getNameNodeHTTPClient(self):
        httpClient = httplib.HTTPConnection(self.namenode_host,
                                            self.namenode_port,
                                            timeout=600)
        return httpClient

    def listdir(self, path):
        if os.path.isabs(path)==False:
            raise Exception("Only absolute paths supported: %s"%(path))

        url_path = WEBHDFS_CONTEXT_ROOT + path+'?op=LISTSTATUS&user.name='+self.username
        httpClient = self.__getNameNodeHTTPClient()
        httpClient.request('GET', url_path, headers={})
        response = httpClient.getresponse()
        data_dict = json.loads(response.read())
        files = []
        for i in data_dict["FileStatuses"]["FileStatus"]:
            files.append(i["pathSuffix"])
        httpClient.close()
        return files

# webhdfs = WebHDFS("10.254.100.139", 50070, "hdfs")
webhdfs = WebHDFS(namenode_host, int(namenode_http_port), "hdfs")
source_files = webhdfs.listdir(source)


Reference:
1. https://hadoop.apache.org/docs/current/hadoop-project-dist/hadoop-hdfs/WebHDFS.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值