
"T`V                 @   s  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 m	 Z	 d  d l
 m Z d  d l m Z d  d l m Z m Z m Z d  d l Z d  d l m Z d  d	 l m Z d  d
 l m Z e j e  Z d Z d Z d Z d Z y d  d l m  Z  d  d l! Z! e! j" d  Z# e  e# j  Z e e  d  k rTd Z e  d  e k owe  d  k  n rd Z Wn e$ k
 rYn Xd d   Z% d d   Z& d d   Z' Gd d   d e(  Z) Gd d   d e)  Z* Gd d   d e(  Z+ Gd d    d  e,  Z- d! d"   Z. d d d  d# d d d d d d d d d d d d$ d%  Z/ d d d d d d# d d d d& d' 	 Z0 Gd( d)   d) e(  Z1 d d* d+  Z2 d, d-   Z3 d S).    N)	parsedate)ENOENT)partial)	NOT_FOUND)count)urlparse
urlunparsequote)
exceptions)log)versionFREDACTED)LooseVersionrequestsz0.8.8Tz0.7.0z1.0.0c             C   sO   t  t |  d d  } | d rE | d rE | d | d <d | d <t |  S)Nschemehttp       )listr   r   )url
parsed_url r   6/usr/lib/python3/dist-packages/cloudinit/url_helper.py	_cleanurl1   s
    
r   c             G   s6   d d   } |  } x | D] } | | |  } q W| S)Nc             S   sl   t  t |    } | d } | r< | j d  r< | d 7} | t t |  d d 7} | | d <t |  S)Nr   /safez/:)r   r   endswithr	   strr   )r   add_onZ
url_parsedpathr   r   r   combine_single=   s    


z#combine_url.<locals>.combine_singler   )baseZadd_onsr!   r   r   r   r   r   combine_url;   s
    	r#   c             K   s#  |  j    }  |  j d  r% d |  }  |  j   j d  r| j d  rY t j d |   |  t d  d  } y) t | d   } | j   } Wd QRXWng t	 k
 r} zG | j
 } | j
 t k r t } t d | d	 | d
 d d |   |  WYd d } ~ Xn Xt | d | St |  |  Sd S)a0  Wrapper function around readurl to allow passing a file path as url.

    When url is not a local file path, passthrough any kwargs to readurl.

    In the case of parameter passthrough to readurl, default values for some
    parameters. See: call-signature of readurl in this module for param docs.
    r   z	file://%szfile://dataz'Unable to post data to file resource %sNrbcausecodeheadersr   contents)lstrip
startswithlowergetLOGwarninglenopenreadIOErrorerrnor   r   UrlErrorFileResponsereadurl)r   kwargs	file_pathfpr)   er'   r   r   r   read_file_or_urlL   s"    
	7r<   c               @   s7   e  Z d  Z d d d  Z d d   Z d d   Z d S)	StringResponse   c             C   s(   | |  _  i  |  _ | |  _ d  |  _ d  S)N)r'   r(   r)   r   )selfr)   r'   r   r   r   __init__l   s    			zStringResponse.__init__c             O   s   |  j  d k r d Sd S)Nr>   FT)r'   )r?   argsr8   r   r   r   okr   s    zStringResponse.okc             C   s   |  j  j d  S)Nzutf-8)r)   decode)r?   r   r   r   __str__w   s    zStringResponse.__str__N)__name__
__module____qualname__r@   rB   rD   r   r   r   r   r=   k   s   r=   c               @   s   e  Z d  Z d d d  Z d S)r6   r>   c             C   s#   t  j |  | d | | |  _ d  S)Nr'   )r=   r@   r   )r?   r    r)   r'   r   r   r   r@   |   s    zFileResponse.__init__N)rE   rF   rG   r@   r   r   r   r   r6   {   s   r6   c               @   s   e  Z d  Z d d   Z e d d    Z e d d    Z d d d	  Z e d
 d    Z e d d    Z	 d d   Z
 d S)UrlResponsec             C   s   | |  _  d  S)N)	_response)r?   responser   r   r   r@      s    zUrlResponse.__init__c             C   s
   |  j  j S)N)rI   content)r?   r   r   r   r)      s    zUrlResponse.contentsc             C   s
   |  j  j S)N)rI   r   )r?   r   r   r   r      s    zUrlResponse.urlFc             C   s=   d } | r d } d |  j  k o, | k  n r5 d Sd Sd  S)Ni,  i  r>   TF)r'   )r?   Zredirects_okupperr   r   r   rB      s    zUrlResponse.okc             C   s
   |  j  j S)N)rI   r(   )r?   r   r   r   r(      s    zUrlResponse.headersc             C   s
   |  j  j S)N)rI   status_code)r?   r   r   r   r'      s    zUrlResponse.codec             C   s
   |  j  j S)N)rI   text)r?   r   r   r   rD      s    zUrlResponse.__str__N)rE   rF   rG   r@   propertyr)   r   rB   r(   r'   rD   r   r   r   r   rH      s   	rH   c               @   s%   e  Z d  Z d d d d d  Z d S)r5   Nc             C   sV   t  j |  t |   | |  _ | |  _ | |  _ |  j d  k rI i  |  _ | |  _ d  S)N)r3   r@   r   r&   r'   r(   r   )r?   r&   r'   r(   r   r   r   r   r@      s    				zUrlError.__init__)rE   rF   rG   r@   r   r   r   r   r5      s   r5   c             C   s   i  } t  |   j } | d k r | r t s@ t j d t  n d | k rg | d rg | d | d <n
 d | d <d | k r d | k r | d | d g | d <n  d | k r t | d  | d <| S)	NhttpszGSSL is not supported in requests v%s, cert. verification can not occur!Zca_certsverifyT	cert_filekey_fileZcert)r   r   SSL_ENABLEDr.   r/   _REQ_VERr   )r   ssl_detailsZssl_argsr   r   r   r   _get_ssl_args   s    	

rW   r   c                s  t  |   }  d |  i } | j t |  |   |
 | d <| sP | rJ d n d } | | d <| d k	 r t t |  d  | d <| d k r g  } t r d	 d
 i } | | d <d } | r t t |  d d  } d d t j   i }   r | j    |   | s  f d d   } | } | r/| | d <| d k rAd } g  } x| rYt	   n t
 d |  D]} | |   | d <i  } x | j   D] \ }  | d k rq| d k r| r f d d   | D } | rt j   | | <x) | D] } t | | | <qWq | | <qWy | rLt j d | | r?d n | |  |  | d k rdt j   } |  } | j |   } Wd QRX|	 r| j   t j d |  | j t | j  | d  t |  SWqft j k
 r} zt | t j  rFt | d  rFt | j d  rF| j t  | d | j j d | j j! d |   n2 | j t  | d |   t" rxt | t j#  rxP| r| | j   | d  rP| r| d k s| d | k  r| d k r| rt j d |  t$ j% |  WYd d } ~ XqfXqfW| r| d  d S)a  Wrapper around requests.Session to read the url and retry if necessary

    :param url: Mandatory url to request.
    :param data: Optional form data to post the URL. Will set request_method
        to 'POST' if present.
    :param timeout: Timeout in seconds to wait for a response
    :param retries: Number of times to retry on exception if exception_cb is
        None or exception_cb returns True for the exception caught. Default is
        to fail with 0 retries on exception.
    :param sec_between: Default 1: amount of seconds passed to time.sleep
        between retries. None or -1 means don't sleep.
    :param headers: Optional dict of headers to send during request
    :param headers_cb: Optional callable returning a dict of values to send as
        headers during request
    :param headers_redact: Optional list of header names to redact from the log
    :param ssl_details: Optional dict providing key_file, ca_certs, and
        cert_file keys for use on in ssl connections.
    :param check_status: Optional boolean set True to raise when HTTPError
        occurs. Default: True.
    :param allow_redirects: Optional boolean passed straight to Session.request
        as 'allow_redirects'. Default: True.
    :param exception_cb: Optional callable which accepts the params
        msg and exception and returns a boolean True if retries are permitted.
    :param session: Optional exiting requests.Session instance to reuse.
    :param infinite: Bool, set True to retry indefinitely. Default: False.
    :param log_req_resp: Set False to turn off verbose debug messages.
    :param request_method: String passed as 'method' to Session.request.
        Typically GET, or POST. Default: POST if data is provided, GET
        otherwise.
    r   allow_redirectsPOSTGETmethodNr   timeoutZstore_cookiesFconfigr   z
User-AgentzCloud-Init/%sc                s     S)Nr   )r   )r(   r   r   _cb
  s    zreadurl.<locals>._cbr$   r(   c                s%   g  |  ] }   j  |  r |  q Sr   )r-   ).0k)vr   r   
<listcomp>  s   	 zreadurl.<locals>.<listcomp>z'[%s/%s] open '%s' with %s configurationinfinitez(Read from %s (%s, %sb) after %s attemptsrJ   rM   r'   z1Please wait %s seconds while we wait to try againrd   rd   )&r   updaterW   maxfloatCONFIG_ENABLEDintr   version_stringr   rangeitemscopydeepcopyr   r.   debugr   ZSessionrequestZraise_for_statusrM   r0   rK   rH   r
   ZRequestException
isinstance	HTTPErrorhasattrrJ   appendr5   r(   rT   ZSSLErrortimesleep)r   r$   r\   retriesZsec_betweenr(   
headers_cbheaders_redactrV   check_statusrX   exception_cbZsessionrc   Zlog_req_resprequest_methodZreq_argsZ
req_configZmanual_triesZdef_headersr^   ZexcpsiZfiltered_req_argsr`   Zmatched_headerskeyZsessrr;   r   )r(   ra   r   r7      s    #



%	
 $
r7   c
             C   s  t  j    }
 d d d  } | d k r- | } d d   } d } d } x| d k	 rf | | |  } n t | d  d } x2|  D]*} t  j    } | d k r | | |
  r P| d k	 r | r | | |
 | k r t |
 | |  } d	 } d } y | d k	 r| |  } n i  } t | d
 | d | d | d d d |	 } | j sd | j } t t |  d | j d
 | j d | } nS | j   sd | j } t t |  d | j d
 | j d | } n | | j f SWni t k
 r} z d | } | } WYd d } ~ Xn5 t	 k
 rE} z d | } | } WYd d } ~ Xn Xt t  j    |
  } | rld | n d } d | | | | f } | |  | r | d | d |  q W| | |
  rP| d } t
 j d |  t  j |  qH Wd S)aI  
    urls:      a list of urls to try
    max_wait:  roughly the maximum time to wait before giving up
               The max time is *actually* len(urls)*timeout as each url will
               be tried once and given the timeout provided.
               a number <= 0 will always result in only one try
    timeout:   the timeout provided to urlopen
    status_cb: call method with string message when a url is not available
    headers_cb: call method with single argument of url to get headers
                for request.
    headers_redact: a list of header names to redact from the log
    exception_cb: call method with 2 arguments 'msg' (per status_cb) and
                  'exception', the exception that occurred.
    sleep_time_cb: call method with 2 arguments (response, loop_n) that
                   generates the next sleep time.
    request_method: indicate the type of HTTP request, GET, PUT, or POST
    returns: tuple of (url, response contents), on failure, (False, None)

    the idea of this routine is to wait for the EC2 metadata service to
    come up.  On both Eucalyptus and EC2 we have seen the case where
    the instance hit the MD before the MD service was up.  EC2 seems
    to have permanently fixed this, though.

    In openstack, the metadata service might be painfully slow, and
    unable to avoid hitting a timeout of even up to 10 seconds or more
    (LP: #894279) for a simple GET.

    Offset those needs with the need to not hang forever (and block boot)
    on a system where cloud-init is configured to look for EC2 Metadata
    service but is not going to find one.  It is possible that the instance
    data host (169.254.169.254) may be firewalled off Entirely for a system,
    meaning that the connection will block forever unless a timeout is set.

    A value of None for max_wait will retry indefinitely.
    Nc             S   s   t  j |   d  S)N)r.   ro   )msgexcr   r   r   log_status_cb  s    z#wait_for_url.<locals>.log_status_cbc             S   s0   |  d  k r d S|  d k p/ t  j    | |  k S)NFr   )ru   )max_wait
start_timer   r   r   timeup  s    zwait_for_url.<locals>.timeupr      r   r   r(   ry   r\   rz   Fr|   zempty response [%s]r'   r   zbad status code [%s]zrequest error [%s]zunexpected error [%s]z%ssZ	unlimitedzCalling '%s' failed [%s/%s]: %sr   	exceptionz1Please wait %s seconds while we wait to try again)FN)ru   ri   r7   r)   r'   r5   
ValueErrorr(   rB   	Exceptionr.   ro   rv   )Zurlsr   r\   	status_cbrx   ry   Z
sleep_timer{   Zsleep_time_cbr|   r   r   r   Zloop_nrJ   r   nowreasonZurl_excr(   r;   Z
time_takenZmax_wait_strZ
status_msgr   r   r   wait_for_urlX  sx    &		




	r   c               @   s   e  Z d  Z d d d d d d d  Z d d   Z d d   Z d	 d
   Z d d   Z d d   Z d d   Z	 d d   Z
 d d   Z d d   Z d S)OauthUrlHelperNz/run/oauth_skew.jsonc             C   s   | |  _  | p d |  _ | |  _ | |  _ | |  _ d |  _ d |  _ |  j |  j |  j  f } t |  su d |  _ n t |  s t	 d   |  j
   } | p i  |  _ d  S)Nr   Tr   FzBall or none of token_key, token_secret, or consumer_key can be set)consumer_keyconsumer_secret	token_keytoken_secretskew_data_file	_do_oauthskew_change_limitanyallr   read_skew_file	skew_data)r?   r   r   r   r   r   requiredoldr   r   r   r@     s    						zOauthUrlHelper.__init__c          	   C   sN   |  j  rJ t j j |  j   rJ t |  j  d d  } t j |  SWd  QRXd  S)Nmoder   )r   osr    isfiler1   jsonload)r?   r:   r   r   r   r     s    zOauthUrlHelper.read_skew_filec          
   C   sn   |  j  s d  S|  j   } | d  k r+ i  } | | | <t |  j  d d  } | j t j |   Wd  QRXd  S)Nr   w)r   r   r1   writer   dumps)r?   hostvaluecurr:   r   r   r   update_skew_file  s    	
zOauthUrlHelper.update_skew_filec       	      C   sF  t  | t  o* | j d k p* | j d k s1 d  Sd | j k rW t j d | j  d  S| j d } y t j t |   } Wn< t	 k
 r } z t j d | |  d  SWYd  d  } ~ Xn Xt
 | t j    } t | j  j } |  j j | d  } t | |  |  j k r5|  j | |  t j d | |  | |  j | <d  S)Ni  i  datez$Missing header 'date' in %s responsez#Failed to convert datetime '%s': %sr   z$Setting oauth clockskew for %s to %d)rq   r5   r'   r(   r.   r/   ru   mktimer   r   ri   r   r   netlocr   r-   absr   r   )	r?   r   r   r   Zremote_timer;   Zskewr   Zold_skewr   r   r   r{     s*    	
zOauthUrlHelper.exception_cbc             C   s   |  j  s i  Sd  } t |  j } |  j rW | |  j k rW t t j    |  j | } t d | d |  j d |  j d |  j	 d |  j
 d |  S)Nr   r   r   r   r   	timestamp)r   r   r   r   ri   ru   oauth_headersr   r   r   r   )r?   r   r   r   r   r   r   rx     s    	zOauthUrlHelper.headers_cbc             C   sK   t  |  j | j d   | d <t  |  j | j d   | d <| | |   S)Nrx   r{   )r   _headers_cbr-   _exception_cb)r?   Zwrapped_funcrA   r8   r   r   r   _wrapped   s
    zOauthUrlHelper._wrappedc             O   s   |  j  t | |  S)N)r   r   )r?   rA   r8   r   r   r   r   '  s    zOauthUrlHelper.wait_for_urlc             O   s   |  j  t | |  S)N)r   r7   )r?   rA   r8   r   r   r   r7   *  s    zOauthUrlHelper.readurlc             C   s7   d  } z | r | | |  } Wd  |  j  | |  X| S)N)r{   )r?   Zextra_exception_cbr   r   retr   r   r   r   -  s    zOauthUrlHelper._exception_cbc             C   s2   i  } | r | |  } | j  |  j |   | S)N)re   rx   )r?   Zextra_headers_cbr   r(   r   r   r   r   6  s
    zOauthUrlHelper._headers_cb)rE   rF   rG   r@   r   r   r{   rx   r   r   r7   r   r   r   r   r   r   r     s   	r   c             C   s   y d d  l  j } Wn4 t k
 rI } z t d  |  WYd  d  } ~ Xn X| r_ t |  } n d  } | j | d | d | d | d | j d | } | j |   \ }	 }
 } |
 S)Nr   zoauth support is not availableZclient_secretZresource_owner_keyZresource_owner_secretZsignature_methodr   )Zoauthlib.oauth1oauth1ImportErrorNotImplementedErrorr   ZClientZSIGNATURE_PLAINTEXTsign)r   r   r   r   r   r   r   r;   clientZ_uriZsigned_headersZ_bodyr   r   r   r   >  s     "		r   c             C   sL   t  | t  s d S| j t k r& d S| j rH t  | j t j  rH d Sd S)zreadurl exception_cb that will retry on NOT_FOUND and Timeout.

    Returns False to raise the exception from readurl, True to retry.
    FT)rq   r5   r'   r   r&   r   ZTimeout)r   r   r   r   r   retry_on_url_excU  s    r   )4rm   r   r   ru   email.utilsr   r4   r   	functoolsr   http.clientr   	itertoolsr   urllib.parser   r   r	   r   r
   	cloudinitr   loggingr   	getLoggerrE   r.   rT   rh   rU   r   Zdistutils.versionr   pkg_resourcesget_distributionZ_REQr   r   r#   r<   objectr=   r6   rH   r3   r5   rW   r7   r   r   r   r   r   r   r   r   <module>   s`   (

!				wn