
    OOId<                         d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
Z
ddlmZmZ ddlmZmZ  e j        d          Z G d d	e          Z G d
 de          ZdS )    N)suppress)quote   )AbstractBufferedFileAbstractFileSystem)infer_storage_optionstokenizewebhdfsc                   V    e Zd ZdZ e ej                              ZdZ	 	 	 	 	 	 	 	 d# fd	Z	e
d             Zd Zd$dZ	 	 	 	 	 d%dZed             Zed             Zed             Zd Zd&dZd Zd Zd Zd'dZd Zd Zd Zd(dZd Zd Zd&dZ d Z!d&dZ"d  Z#d! Z$d" Z% xZ&S ))WebHDFSa~  
    Interface to HDFS over HTTP using the WebHDFS API. Supports also HttpFS gateways.

    Three auth mechanisms are supported:

    insecure: no auth is done, and the user is assumed to be whoever they
        say they are (parameter ``user``), or a predefined value such as
        "dr.who" if not given
    spnego: when kerberos authentication is enabled, auth is negotiated by
        requests_kerberos https://github.com/requests/requests-kerberos .
        This establishes a session based on existing kinit login and/or
        specified principal/password; parameters are passed with ``kerb_kwargs``
    token: uses an existing Hadoop delegation token from another secured
        service. Indeed, this client can also generate such tokens when
        not insecure. Note that tokens expire, but can be renewed (by a
        previously specified user) and may allow for proxying.

    )r
   webHDFS  FNc
                    | j         rdS  t                      j        di |
 d                    |	rdnd||          | _        || _        |pi | _        i | _        |pi | _        |||t          d          || j        d<   |
|| j        d<   |
|| j        d	<   |r|t          d
          | 
                                 dt          ||          z   | _        dS )a  
        Parameters
        ----------
        host: str
            Name-node address
        port: int
            Port for webHDFS
        kerberos: bool
            Whether to authenticate with kerberos for this connection
        token: str or None
            If given, use this token on every call to authenticate. A user
            and user-proxy may be encoded in the token and should not be also
            given
        user: str or None
            If given, assert the user name to connect with
        proxy_to: str or None
            If given, the user has the authority to proxy, and this value is
            the user in who's name actions are taken
        kerb_kwargs: dict
            Any extra arguments for HTTPKerberosAuth, see
            `<https://github.com/requests/requests-kerberos/blob/master/requests_kerberos/kerberos_.py>`_
        data_proxy: dict, callable or None
            If given, map data-node addresses. This can be necessary if the
            HDFS cluster is behind a proxy, running on Docker or otherwise has
            a mismatch between the host-names given by the name-node and the
            address by which to refer to them from the client. If a dict,
            maps host names ``host->data_proxy[host]``; if a callable, full
            URLs are passed, and function must conform to
            ``url->data_proxy(url)``.
        use_https: bool
            Whether to connect to the Name-node using HTTPS instead of HTTP
        kwargs
        Nz%{protocol}://{host}:{port}/webhdfs/v1httpshttp)protocolhostportz_If passing a delegation token, must not set user or proxy_to, as these are encoded in the token
delegationz	user.namedoaszJIf using Kerberos auth, do not specify the user, this is handled by kinit.webhdfs_ )_cachedsuper__init__formaturlkerbkerb_kwargsparsproxy
ValueError_connectr	   _fsid)selfr   r   kerberostokenuserproxy_tor   
data_proxy	use_httpskwargs	__class__s              >lib/python3.11/site-packages/fsspec/implementations/webhdfs.pyr   zWebHDFS.__init__+   s/   \ < 	F""6""":AA )5WWvDt B 
 
 	&,"	%2
8#7   
 ',DIl#%)DIk" (DIf 	(2   	(4"6"66


    c                     | j         S N)r$   r%   s    r.   fsidzWebHDFS.fsidx   s
    zr/   c                     t          j                    | _        | j        rddlm}  |di | j        | j        _        d S d S )Nr   )HTTPKerberosAuthr   )requestsSessionsessionr   requests_kerberosr5   r   auth)r%   r5   s     r.   r#   zWebHDFS._connect|   s_    '))9 	E:::::: 0 0 D D43C D DDL	E 	Er/   getTc                    | j         t          |pd          z   }|                                }|                    | j                   |                                |d<   t                              d||           | j        	                    |                                ||||          }	|	j
        dv r	 |	                                }
|
d         d         }|
d         d         }|d	v rt          |          |d
v rt          |          |dv rt          |          t          |          # t          t           f$ r Y nw xY w|	                                 |	S )N opzsending %s with %s)methodr   paramsdataallow_redirects)i  i  i  i  i  RemoteExceptionmessage	exception)IllegalArgumentExceptionUnsupportedOperationException)SecurityExceptionAccessControlException)FileNotFoundException)r   r   copyupdater    upperloggerdebugr8   requeststatus_codejsonr"   PermissionErrorFileNotFoundErrorRuntimeErrorKeyErrorraise_for_status)r%   r>   r?   pathrA   redirectr,   r   argsouterrmsgexps                r.   _callzWebHDFS._call   st   htzr***{{}}DIXXZZT
)3777l""<<>>$ # 
 
 ?777,hhjj+,Y7+,[9 WWW$S//)KKK)#...555+C000&s+++ )    	
s   60D. .EErbc           
      L    |p| j         }t          | |||| j        |||          S )a^  

        Parameters
        ----------
        path: str
            File location
        mode: str
            'rb', 'wb', etc.
        block_size: int
            Client buffer size for read-ahead or write buffer
        autocommit: bool
            If False, writes to temporary file that only gets put in final
            location upon commit
        replication: int
            Number of copies of file on the cluster, write mode only
        permissions: str or int
            posix permissions, write mode only
        kwargs

        Returns
        -------
        WebHDFile instance
        )mode
block_sizetempdir
autocommitreplicationpermissions)	blocksize	WebHDFilerd   )r%   rX   rb   rc   re   rf   rg   r,   s           r.   _openzWebHDFS._open   sB    B  14>
!L!##	
 	
 	
 		
r/   c                 V    | d                                          | d<   | d         | d<   | S )Ntypelengthsize)lower)infos    r.   _process_infozWebHDFS._process_info   s-    F|))++VH~Vr/   c                 ,    t          |          d         S )NrX   )r   )clsrX   s     r.   _strip_protocolzWebHDFS._strip_protocol   s    $T**622r/   c                     t          |           }|                    dd            |                    dd            d|v r|                    d          |d<   |S )NrX   r   usernamer(   )r   pop)urlpathr[   s     r.   _get_kwargs_from_urlszWebHDFS._get_kwargs_from_urls   s\    #G,,
D!!!''*--CK
r/   c                     |                      d|          }|                                d         }||d<   |                     |          S )NGETFILESTATUSrX   
FileStatusname)r_   rR   rq   )r%   rX   r[   rp   s       r.   rp   zWebHDFS.info   sF    jjtj44xxzz,'V!!$'''r/   c                 F   |                      d|          }|                                d         d         }|D ];}|                     |           |                    d          dz   |d         z   |d<   <|rt	          |d 	          S t	          d
 |D                       S )N
LISTSTATUSr|   FileStatusesr}   /
pathSuffixr~   c                     | d         S )Nr~   r   )is    r.   <lambda>zWebHDFS.ls.<locals>.<lambda>   s
    qy r/   )keyc              3   &   K   | ]}|d          V  dS )r~   Nr   ).0rp   s     r.   	<genexpr>zWebHDFS.ls.<locals>.<genexpr>   s&      994$v,999999r/   )r_   rR   rq   rstripsorted)r%   rX   detailr[   infosrp   s         r.   lsz
WebHDFS.ls   s    jjDj11

>*<8 	G 	GDt$$$;;s++c1D4FFDLL 	:%%8%89999995999999r/   c                 d    |                      d|          }|                                d         S )z8Total numbers of files, directories and bytes under pathGETCONTENTSUMMARYr|   ContentSummaryr_   rR   )r%   rX   r[   s      r.   content_summaryzWebHDFS.content_summary   s,    jj,4j88xxzz*++r/   c                 p   |                      d|d          }d|j        v rh|                     |j        d                   }| j                            |          }|                                 |                                d         S |                                 |                                d         S )z/Checksum info of file, giving method and resultGETFILECHECKSUMF)rX   rY   LocationFileChecksum)r_   headers_apply_proxyr8   r;   rW   rR   )r%   rX   r[   locationout2s        r.   ukeyzWebHDFS.ukey   s    jj*jFF$$((Z)@AAH<##H--D!!###99;;~..  """88::n--r/   c                 `    |                      d          }|                                d         S )zGet user's home directoryGETHOMEDIRECTORYPathr   )r%   r[   s     r.   home_directoryzWebHDFS.home_directory  s'    jj+,,xxzz&!!r/   c                     |r|                      d|          }n|                      d          }|                                d         }|t          d          |d         S )zRetrieve token which can give the same authority to other uses

        Parameters
        ----------
        renewer: str or None
            User who may use this token; if None, will be current user
        GETDELEGATIONTOKEN)renewerTokenNz1No token available for this user/security context	urlString)r_   rR   r"   )r%   r   r[   ts       r.   get_delegation_tokenzWebHDFS.get_delegation_token
  sf      	3**17*CCCC**122CHHJJw9PQQQ~r/   c                 f    |                      dd|          }|                                d         S )z/Make token live longer. Returns new expiry timeRENEWDELEGATIONTOKENputr?   r'   longr   )r%   r'   r[   s      r.   renew_delegation_tokenzWebHDFS.renew_delegation_token  s-    jj/UjKKxxzz&!!r/   c                 6    |                      dd|           dS )z Stop the token from being usefulCANCELDELEGATIONTOKENr   r   Nr_   )r%   r'   s     r.   cancel_delegation_tokenzWebHDFS.cancel_delegation_token   s!    

*5
FFFFFr/   c                 8    |                      dd||           dS )a  Set the permission at path

        Parameters
        ----------
        path: str
            location to set (file or directory)
        mod: str or int
            posix epresentation or permission, give as oct string, e.g, '777'
            or 0o777
        SETPERMISSIONr   )r?   rX   
permissionNr   )r%   rX   mods      r.   chmodzWebHDFS.chmod$  s$     	

?5t
LLLLLr/   c                 F    i }|||d<   |||d<    | j         dd|d| dS )zChange owning user and/or groupNownergroupSETOWNERr   r?   rX   )r   r   )r%   rX   r   r   r,   s        r.   chownzWebHDFS.chown1  sJ    #F7O#F7O
Ae$AA&AAAAAr/   c                 8    |                      d|d|           dS )a9  
        Set file replication factor

        Parameters
        ----------
        path: str
            File location (not for directories)
        replication: int
            Number of copies of file on the cluster. Should be smaller than
            number of data nodes; normally 3 on most systems.
        SETREPLICATIONr   )rX   r?   rf   Nr   )r%   rX   rf   s      r.   set_replicationzWebHDFS.set_replication:  s%     	

#$u+
VVVVVr/   c                 6    |                      dd|           d S )NMKDIRSr   r   r   r%   rX   r,   s      r.   mkdirzWebHDFS.mkdirH  s     

8E
55555r/   c                     |du r$|                      |          rt          |          |                     |           d S )NF)existsFileExistsErrorr   )r%   rX   exist_oks      r.   makedirszWebHDFS.makedirsK  sD    uT!2!2!$'''

4r/   c                 8    |                      dd||           d S )NRENAMEr   )r?   rX   destinationr   )r%   path1path2r,   s       r.   mvz
WebHDFS.mvP  s"    

8E5
IIIIIr/   c                 @    |                      dd||rdnd           d S )NDELETEdeletetruefalse)r?   rX   	recursiver   )r%   rX   r   r,   s       r.   rmz
WebHDFS.rmS  s<    

 )6ffw	 	 	
 	
 	
 	
 	
r/   c                 0    |                      |           d S r1   )r   r   s      r.   rm_filezWebHDFS.rm_file[  s    r/   c                 8   |                      |          5 }d                    |                     |          dt          j        d           g          }	 |                      |d          5 }t          j        ||           d d d            n# 1 swxY w Y   |                     ||           nP# t          $ rC t          t                    5  |                     |           d d d            n# 1 swxY w Y    w xY w	 d d d            d S # 1 swxY w Y   d S )Nr   z.tmp.   wb)openjoin_parentsecrets	token_hexshutilcopyfileobjr   BaseExceptionr   rT   r   )r%   lpathrpathr,   lstream	tmp_fnamerstreams          r.   cp_filezWebHDFS.cp_file^  s   YYu 	$,,u"5"57Vw?PQS?T?T7V7V!WXXIYYy$// 97&w8889 9 9 9 9 9 9 9 9 9 9 9 9 9 9	5))))    /00 ' 'GGI&&&' ' ' ' ' ' ' ' ' ' ' ' ' ' ' *	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	sr   A DB1-BB1B	B1B	B10D1C>C1%C>1C55C>8C59C>>DDDc                     | j         r*t          | j                   r|                      |          }n=| j         r6| j                                         D ]\  }}|                    ||d          }|S )N   )r!   callableitemsreplace)r%   r   kvs       r.   r   zWebHDFS._apply_proxyl  sy    : 	5(4:.. 	5zz(++HHZ 	5
((** 5 51#++Aq!44r/   )r   FNNNNNF)r;   NNT)r`   NTNNFr1   )NN)'__name__
__module____qualname____doc__strtempfile
gettempdirrd   r   r   propertyr3   r#   r_   rj   staticmethodrq   classmethodrt   ry   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r-   s   @r.   r   r      sz        & c%(%''((G#H
 K7 K7 K7 K7 K7 K7Z   XE E E   F +
 +
 +
 +
Z   \
 3 3 [3   \( ( (	: 	: 	: 	:, , ,

. 
. 
." " "
   "" " "
G G GM M MB B B BW W W6 6 6   
J J J
 
 
 
          r/   r   c                   B     e Zd ZdZ fdZd	dZd Zd Zd Zd Z	 xZ
S )
ri   z"A file living in HDFS over webHDFSc                 H    t                      j        ||fi | |                                }|                    dd           |                    dd            |                    dd           |                    dd            |                    dd          | _        |                    d          }|                    dd          du rQ| j        | _        t          j        	                    |t          t          j                                        | _        d S d S )Nrg   rf   i  rd   re   F)r   r   rK   r;   rw   rg   rX   targetosr   r   uuiduuid4)r%   fsrX   r,   rd   r-   s        r.   r   zWebHDFile.__init__y  s    T,,V,,,::mT**2JJ}d+++::mT**2JJ}d+++!::mS99**Y''::lE**e33)DKWc$*,,.?.?@@DIII 43r/   Fc                     | j         j                            | j        | j                                        ddi          }|                                 dS )zWrite one part of a multi-block file upload

        Parameters
        ==========
        final: bool
            This is the last block, so should complete file, if
            self.autocommit is True.
        content-typeapplication/octet-stream)rA   r   T)r  r8   postr   buffergetvaluerW   )r%   finalr[   s      r.   _upload_chunkzWebHDFile._upload_chunk  sZ     go""M%%''#%?@ # 
 

 	tr/   c                    | j                                         }d| j        v rd\  }}n
d\  }}d|d<    | j        j        ||| j        fddi|}| j                            |j        d                   }d	| j        v r| j        j        	                    |d
di          }|
                                  | j        j        dd| j        fddi|}| j                            |j        d                   | _        dS dS )zCreate remote file/uploada)APPENDPOST)CREATEPUTr   	overwriterY   Fr   wr  r  )r   r  r  N)r,   rK   rb   r  r_   rX   r   r   r8   r   rW   r   )r%   r,   r>   r?   r[   r   r   s          r.   _initiate_uploadzWebHDFile._initiate_upload  s   !!##$))JB(JB"(F;dgmB	LLELVLL7''J(?@@$)7?&&>3M"N '  D !!### 47=649WWuWPVWWD G00j1IJJDMMM r/   c                    t          |d          }t          | j        |          }||k    s|| j        k    rdS | j                            d| j        |||z
  d          }|                                 d|j        v rK|j        d         }| j        j        	                    | j        
                    |                    }|j        S |j        S )Nr   r/   OPENF)rX   offsetrm   rY   r   )maxminrn   r  r_   rX   rW   r   r8   r;   r   content)r%   startendr[   r   r   s         r.   _fetch_rangezWebHDFile._fetch_range  s    E1$)S!!C<<5DI--3gmm5uu  
 
 	$${:.H7?&&tw';';H'E'EFFD<;r/   c                 P    | j                             | j        | j                   d S r1   )r  r   rX   r   r2   s    r.   commitzWebHDFile.commit  s"    

49dk*****r/   c                 D    | j                             | j                   d S r1   )r  r   rX   r2   s    r.   discardzWebHDFile.discard  s    

49r/   r   )r   r   r   r   r   r  r  r  r   r"  r   r   s   @r.   ri   ri   v  s        ,,A A A A A   "K K K(   + + +      r/   ri   )loggingr  r   r   r   r  
contextlibr   urllib.parser   r6   specr   r   utilsr   r	   	getLoggerrN   r   ri   r   r/   r.   <module>r)     s    				                  ; ; ; ; ; ; ; ; 3 3 3 3 3 3 3 3		9	%	%_ _ _ _ _  _ _ _DI I I I I$ I I I I Ir/   