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

猜你喜欢

转载自blog.csdn.net/yeruby/article/details/51448166