HdfsCLI

repository·master·Indexed 43 days ago

https://github.com/mtth/hdfs

A Python library and command-line interface for interacting with HDFS via WebHDFS and HttpFS APIs. It supports secure and insecure clusters, including Kerberos authentication, and provides extensions for Avro and Pandas dataframes.

Tokens
7.1K
Snippets
24
Records
37
Agent score
55%

What's inside HdfsCLI

  1. HdfsCLI Features and Extensions

    master

    HdfsCLI provides Python 3 bindings for WebHDFS and HttpFS, supporting both secure and insecure clusters. It also supports optional extensions for specialized tasks:

    • avro: Read and write Avro files directly from HDFS.
    • dataframe: Load and save Pandas dataframes.
    • kerberos: Support for Kerberos authenticated clusters.
  2. Use HDFS Extensions (Kerberos, Avro, Dataframe)

    master

    The hdfs library provides several extensions to enhance functionality:

    • Kerberos: Use hdfs.ext.kerberos for authenticated connections to HDFS clusters using Kerberos.
    • Avro: Use hdfs.ext.avro to work with Avro data formats within HDFS.
    • Dataframe: Use hdfs.ext.dataframe to integrate HDFS operations with dataframes (typically for pandas-like workflows).
  3. Check if an HDFS path exists

    master

    Most HDFS methods raise an hdfs.util.HdfsError if the target path does not exist. To check for existence without triggering an error, use the content or status methods with the strict=False argument. If the path is missing, these methods will return None.

    # Returns None if path does not exist instead of raising HdfsError
    if client.status('my/path', strict=False) is not None:
        print("Path exists")
  4. Configure HdfsCLI aliases

    master

    HdfsCLI uses aliases to manage connections to different HDFS clusters. These are defined in a configuration file located at ~/.hdfscli.cfg by default, or at a custom path specified by the HDFSCLI_CONFIG environment variable.

    Each alias is defined in a section named ALIAS.alias. A valid alias section must include a url option (the WebHDFS namenode URL, including protocol and port). You can also specify a client class to change the connection type and a root path for the cluster.

    Supported client classes:

    • hdfs.client.InsecureClient (default)
    • hdfs.client.TokenClient (for Kerberos/Token-based auth)
    • hdfs.ext.kerberos.KerberosClient (via Kerberos extension)

    To support High Availability (HA) namenodes with WebHDFS, provide multiple URLs delimited by a semicolon (;) in the url option. Use the [global] section to set a default.alias.

    [global]
    default.alias = dev
    
    [dev.alias]
    url = http://dev.namenode:port
    user = ann
    
    [prod.alias]
    url = http://prod.namenode:port
    root = /jobs/
  5. Rename the HdfsCLI entry point

    master

    By default, the command line entry point is named hdfscli. You can change this name during installation by setting the HDFSCLI_ENTRY_POINT environment variable.

    Note that extension prefixes will be adjusted accordingly (e.g., if you rename the entry point to hdfs, hdfscli-avro becomes hdfs-avro).

    Example:

    $ HDFSCLI_ENTRY_POINT=hdfs pip install hdfs
    $ HDFSCLI_ENTRY_POINT=hdfs pip install hdfs
  6. Configure custom client support for HdfsCLI

    master

    To use arbitrary client classes in the HdfsCLI, you must first make them discoverable by specifying their location in the [global] section of the HdfsCLI configuration file.

    You can use two options to tell the CLI where to load clients from:

    • autoload.modules: A comma-separated list of Python modules (must be on Python's path).
    • autoload.paths: A comma-separated list of paths to Python files.

    Example: making hdfs.ext.kerberos.KerberosClient available:

    [global]
    autoload.modules = hdfs.ext.kerberos

    Example: loading a custom client from a specific file path and defining an alias:

    [global]
    autoload.paths = /etc/hdfscli.py
    
    [prod.alias]
    client = SecureClient
    url = https://host:port
    cert = /etc/server.crt, /etc/key

    Note: Options passed to clients from the CLI (via hdfs.client.Client.from_options) are always passed as strings. You may need to implement parsing logic in your custom client's __init__ method.

    [global]
    autoload.modules = hdfs.ext.kerberos
  7. Install HdfsCLI via pip

    master

    Install the core hdfs package using pip. Note that by default, extension requirements are not installed. To include specific extensions like avro, dataframe, or kerberos, use the bracket syntax during installation.

    $ pip install hdfs
    
    # To install with extensions:
    $ pip install hdfs[avro,dataframe,kerberos]
  8. Use path expansion with #LATEST

    master

    The hdfs.client.Client methods support path expansion via the resolve method. This allows you to use special markers in your paths. The #LATEST marker expands to the last modified file within a specified folder.

    Example usage:

    # Load the most recent data in the `tracking` folder.
    with client.read('tracking/#LATEST') as reader:
        data = reader.read()
    with client.read('tracking/#LATEST') as reader:
        data = reader.read()
  9. Use the HdfsCLI command line interface

    master

    The hdfscli entry point allows performing common HDFS operations. All commands accept an --alias argument to specify which cluster configuration to use.

    Uploading and Downloading

    • Upload: Use upload to send files or folders to HDFS. Use --threads to specify parallelism.
    • Download: Use download to retrieve files or folders. Use --threads for parallelism.
    • Overwrite: By default, HdfsCLI prevents overwriting existing paths. Use the --force option to overwrite.
    • Streaming: Use - as a path argument to stream a single file's contents to/from standard out/in.

    Interactive Shell

    Running hdfscli --alias=YOUR_ALIAS (or just hdfscli if a default is set) opens an interactive Python shell (using IPython if available). The HDFS client is automatically available as the variable CLIENT.

    # Write a single file to HDFS
    hdfscli upload --alias=dev weights.json models/
    
    # Read all files inside a folder from HDFS and store them locally
    hdfscli download export/results/ "results-$(date +%F)"
    
    # Read a file from HDFS and append its contents to a local log file using stdout
    hdfscli download logs/1987-03-23.txt - >>logs
    
    # Interactive shell usage
    $ hdfscli --alias=dev
    In [1]: CLIENT.list('data/')
    In [2]: CLIENT.status('data/2.json')
  10. Track transfer progress with callbacks

    master

    The hdfs.client.Client.read, hdfs.client.Client.upload, and hdfs.client.Client.download methods accept a progress callback argument.

    The callback function is invoked every chunk_size bytes and receives two arguments:

    1. hdfs_path: The source path of the file currently being transferred.
    2. nbytes: The number of bytes currently transferred for this file, or -1 to signal that the file transfer has finished.

    Note: The write method does not expose a progress argument; instead, you can achieve similar functionality by passing a custom data generator.

    Example implementation of a progress tracker:

    from sys import stderr
    from threading import Lock
    
    class Progress(object):
        """Basic progress tracker callback."""
        def __init__(self):
            self._data = {}
            self._lock = Lock()
    
        def __call__(self, hdfs_path, nbytes):
            with self._lock:
                if nbytes >= 0:
                    self._data[hdfs_path] = nbytes
                else:
                    stderr.write('%s\n' % (sum(self._data.values()), ))
    class Progress(object):
        def __init__(self):
            self._data = {}
            self._lock = Lock()
    
        def __call__(self, hdfs_path, nbytes):
            with self._lock:
                if nbytes >= 0:
                    self._data[hdfs_path] = nbytes
                else:
                    stderr.write('%s\n' % (sum(self._data.values()), ))
  11. Configure logging for HdfsCLI entry points

    master

    You can configure or disable logging for specific HdfsCLI entry points by adding configuration to the entry point's section, using the suffix .command.

    Available options:

    • log.level: The handler log level (defaults to DEBUG).
    • log.path: Path to the log file. Logs are rotated daily (keeping a single copy). The default is a file named COMMAND.log in your current temporary directory. You can view the active log file using the --log CLI option.
    • log.disable: Set to True to disable logging to a file entirely (defaults to False).

    Example configuration for an avro entry point:

    [hdfscli-avro.command]
    log.level = INFO
    log.path = /tmp/hdfscli/avro.log
    [hdfscli-avro.command]
    log.level = INFO
    log.path = /tmp/hdfscli/avro.log