3 \meCm@sddlZddlZddlZddlZddlZddlZddlmZmZm Z ddl m Z ddl m Z ddlmZddlmZddlmZddlmZmZmZmZmZmZmZdd lmZmZmZddl Z dd l m!Z!dd l"m#Z#ej$e%Z&d Z'd dZ(ddZ)ed5dddZ*GdddZ+Gddde+Z,GdddZ-Gddde.Z/ddZ0d6e1e-d"d#d$Z2d7ed%efe3e4ej5ee6ed&d'd(Z7d8ed%efee3e6e4ed+d,d-Z8dde&j9dddddd!dd)f eeee4eeeeee4ge4fe3e1e6d.d/d0Z:Gd1d2d2Z;d9d3d4Ztt|dd}|d r6|dr6|d|d<d|d<t|S)NZhttp)scheme)listrr)urlZ parsed_urlr /usr/lib/python3.6/url_helper.py _cleanurl$s  rcGs(dd}|}x|D]}|||}qW|S)NcSsPtt|}|d}|r,|jd r,|d7}|tt|dd7}||d<t|S)Nr/z/:)Zsafe)rrendswithrstrr)radd_onZ url_parsedpathrrrcombine_single/s z#combine_url..combine_singler)baseZadd_onsr%rr#rrr combine_url.s   r' FileResponse UrlResponse)returncKs|j}|jdrd|}|jjdr|jdr>tjd||tdd}y"t|d}|j}WdQRXWnHt k r}z,|j }|j t krt }t ||d|d|WYdd}~XnXt||d St|f|SdS) a0Wrapper 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://%szfile://dataz'Unable to post data to file resource %sNrb)causecodeheadersr)contents)lstrip startswithlowergetLOGwarninglenopenreadIOErrorerrnorrUrlErrorr(readurl)rkwargsZ file_pathfpr0er.rrrread_file_or_url>s"     $ rAc@s&eZdZd ddZddZddZdS) StringResponsecCs||_i|_||_d|_dS)N)r.r/r0r)selfr0r.rrr__init__^szStringResponse.__init__cOs|jdkrdSdS)NrCFT)r.)rDargsr>rrrokds zStringResponse.okcCs |jjdS)Nzutf-8)r0decode)rDrrr__str__iszStringResponse.__str__N)rC)__name__ __module__ __qualname__rErGrIrrrrrB]s rBc@seZdZdddZdS)r(rCcCstj|||d||_dS)N)r.)rBrEr)rDr$r0r.rrrrEnszFileResponse.__init__N)rC)rJrKrLrErrrrr(msc@seZdZejdddZeedddZeddZ dd d Z ed d Z eddZ ddZ deeeeedddZdS)r))responsecCs ||_dS)N) _response)rDrMrrrrEtszUrlResponse.__init__)r*cCs|jjdkrdS|jjS)N)rNcontent)rDrrrr0ws zUrlResponse.contentscCs|jjS)N)rNr)rDrrrr}szUrlResponse.urlFcCs2d}|r d}d|jko |knr*dSdSdS)Ni,irCTF)r.)rDZ redirects_okupperrrrrGs zUrlResponse.okcCs|jjS)N)rNr/)rDrrrr/szUrlResponse.headerscCs|jjS)N)rN status_code)rDrrrr.szUrlResponse.codecCs|jjS)N)rNtext)rDrrrrIszUrlResponse.__str__r) chunk_sizedecode_unicoder*ccs|jj||EdHdS)atIterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. :param chunk_size: Number of bytes it should read into memory. :param decode_unicode: If True, content will be decoded using the best available encoding based on the response. N)rN iter_content)rDrTrUrrrrVs zUrlResponse.iter_contentN)F)rF)rJrKrLrequestsZResponserEpropertybytesr0rrGr/r.rIrintboolr rVrrrrr)ss    c@seZdZdddZdS)r<NcCs<tj|t|||_||_||_|jdkr2i|_||_dS)N)r:rEr"r-r.r/r)rDr-r.r/rrrrrEs zUrlError.__init__)NNN)rJrKrLrErrrrr<sr<cCsi}t|j}|dkr~|r~d|kr8|dr8|d|d<nd|d<d|krfd|krf|d|dg|d<nd|kr~t|d|d<|S)NZhttpsZca_certsZverifyTZ cert_fileZkey_fileZcert)rrr")r ssl_detailsZssl_argsrrrr _get_ssl_argss  r]rTFr)streamr*cs"t|}||d}|jt||| |d<|s:|r6dnd}||d<|dk rpt|tr^||d<ntt|d|d<|dkr|g}d }|rtt|d d }d d tj i}r|j||ṡfd d }|}|r||d<|dkrd}g}x*| rt nt d|D]}|||d<i}x|j D]t\}|dkr6q |dkr|rfdd|D}|rt j||<x$|D]}t|||<qrWn||<q Wy|rtjd|| rdn|||| dkrtj} | }|jf|}WdQRX| r|jtjd||jt|j|d t|Stjk r}zt|tjrzt|drzt|jdrz|jt ||jj|jj!|dn"|jt ||dt|tj"rP| r| |j |d rP| r|dks|d |kr|dkr|rtjd|t#j$|WYdd}~XnXqW|ddS)aWrapper 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. May be a tuple if specifying (connection timeout, read timeout). :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. :param stream: if False, the response content will be immediately downloaded. )rr^allow_redirectsZPOSTZGETmethodNtimeoutrrz User-Agentz Cloud-Init/%scsS)Nr)r)r/rr_cbszreadurl.._cbr+r/csg|]}j|r|qSr)r4).0k)vrr 'szreadurl..z'[%s/%s] open '%s' with %s configurationinfinitez(Read from %s (%s, %sb) after %s attemptsrMrR)r.r/r)rz1Please wait %s seconds while we wait to try againrhrh)%rupdater] isinstancetuplemaxfloatrZrZversion_stringr rangeitemscopydeepcopyrr5debugrWZSessionZrequestZraise_for_statusrRr7rPr)rZRequestExceptionZ HTTPErrorhasattrrMappendr<r/ZSSLErrortimesleep)rr+raZretriesZ sec_betweenr/ headers_cbheaders_redactr\ check_statusr_ exception_cbZsessionrgZ log_req_resprequest_methodr^Zreq_argsZ manual_triesZ def_headersrbZexcpsiZfiltered_req_argsrdZmatched_headerskeyZsessrr@r)r/rerr=s4              "r=.)funcaddrraeventdelayr*cCs|r|j|drdS|||S)z Execute func with optional delay)raN)wait)rrrarrrrr_run_func_with_delayus r333333? )r addresses stagger_delayrar*c sd}d}d}g}tjtt|dzyfddt|D}xTt|dD]D} || }| j} | r~| }|j|qV| j}|rVj ||fSqVW|rt j d|||nt j d|t dWn.tk rt j d d j|d j|YnXWdjd d X||fS) aexecute multiple callbacks in parallel Run blocking func against two different addresses staggered with a delay. The first call to return successfully is returned from this function and remaining unfinished calls are cancelled if they have not yet started N) max_workersc s,i|]$\}}|jt||dqS))rrrarr)Zsubmitr)rcr|r)executorris_donerrarr s zdual_stack..)raz.default_sleep_timecSs$|dkr dS|dkp"tj||kS)z4Check if time is up based on start time and max waitNFr)ru)max_wait start_timerrrtimeupszwait_for_url..timeupcSsf|js*d|j}tt||j|j|d}n4|jsVd|j}tt||j|j|d}nd}d}||fS)z?Map requests response code/contents to internal "UrlError" typezempty response [%s])r.r/rzbad status code [%s]rN)r0r.r<rr/rG)rMrreasonurl_excrrrhandle_url_responses"    z)wait_for_url..handle_url_responsec sd}d}y*||\}}||\}}|s0||fSWnZtk r`} zd| }| }WYdd} ~ Xn.tk r} zd| }| }WYdd} ~ XnXttj|} rdnd} d|| | |f} || |r|| |ddS) z:Execute request, handle response, optionally log exceptionrNzrequest error [%s]zunexpected error [%s]z%ssZ unlimitedzCalling '%s' failed [%s/%s]: %s)msgr)r< ExceptionrZru) Z url_reader_cburlsrexc_cblog_cbrrrMrr@Z time_takenZ max_wait_strZ status_msg)rrrrread_url_handle_exceptions.s.  z0wait_for_url..read_url_handle_exceptionscs$t|dkrin||ddS)NF)r/rxraryr{)r=)rra)rwrxr{rr read_url_cbNsz!wait_for_url..read_url_cbcsfdd}xnD]f}tj}dkrb|r6dSdk rbrb||krbt|||||||}|r|SqWdS)z|iterate over list of urls, request each one and handle responses and thrown exceptions individually per url cs||fS)Nr)r)rrarrurl_reader_serial]sz@wait_for_url..read_url_serial..url_reader_serialrN)rurZ)rrarrrrZnowout)loop_nrrrrr)rarread_url_serialXs  z%wait_for_url..read_url_serialcs,tt|d}||||}|r(|SdS)zpass list of urls to dual_stack which sends requests in parallel handle response and exceptions of the first endpoint to respond )rraN)rr)rrarrZurl_reader_parallelr)rrrrrrread_url_parallelssz'wait_for_url..read_url_parallelrNrz1Please wait %s seconds while we wait to try againz$Timed out, no response from urls: %sF)FN)rZrur0r5rrrvr)rrrarrwrxrrzrr{rrrrrrZ do_read_urlZcalculate_sleep_timerMrZaddressr) rrrwrxrrrrr{rrr wait_for_urls64        rc@s^eZdZdddZddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ dS)OauthUrlHelperN/run/oauth_skew.jsoncCst||_|p d|_||_||_||_d|_d|_|j|j|jf}t|sNd|_nt|s^t d|j }|pli|_ dS)NrTrFzBall or none of token_key, token_secret, or consumer_key can be set) consumer_keyconsumer_secret token_key token_secretskew_data_file _do_oauthskew_change_limitanyallrread_skew_file skew_data)rDrrrrrZrequiredoldrrrrEs zOauthUrlHelper.__init__c Cs8|jr4tjj|jr4t|jdd }tj|SQRXdS)Nr~)mode)rosr$isfiler8jsonload)rDr?rrrrszOauthUrlHelper.read_skew_filec CsT|js dS|j}|dkri}|||<t|jdd}|jtj|WdQRXdS)Nw)r)rrr8writerdumps)rDhostvalueZcurr?rrrupdate_skew_fileszOauthUrlHelper.update_skew_filec Cst|to|jdkp|jdks"dSd|jkr>tjd|jdS|jd}ytjt|}Wn.t k r}ztjd||dSd}~XnXt |tj}t |j j }|jj|d}t|||jkr|j||tjd||||j|<dS)Niidatez$Missing header 'date' in %s responsez#Failed to convert datetime '%s': %srz$Setting oauth clockskew for %s to %d)rjr<r.r/r5r6ruZmktimerrrZrrnetlocrr4absrr) rDrrrZ remote_timer@ZskewrZold_skewrrrrzs(      zOauthUrlHelper.exception_cbcCsZ|js iSd}t|j}|jr>||jkr>ttj|j|}t||j|j|j |j |dS)N)rrrrr timestamp) rrrrrZru oauth_headersrrrr)rDrrrrrrrws zOauthUrlHelper.headers_cbcCs6t|j|jd|d<t|j|jd|d<|||S)Nrwrz)r _headers_cbr4 _exception_cb)rDZ wrapped_funcrFr>rrr_wrappeds zOauthUrlHelper._wrappedcOs|jt||S)N)rr)rDrFr>rrrrszOauthUrlHelper.wait_for_urlcOs|jt||S)N)rr=)rDrFr>rrrr=szOauthUrlHelper.readurlc Cs*d}z|r|||}Wd|j||X|S)N)rz)rDZextra_exception_cbrrretrrrrs zOauthUrlHelper._exception_cbcCs$i}|r||}|j|j||S)N)rirw)rDZextra_headers_cbrr/rrrrs zOauthUrlHelper._headers_cb)NNNNr) rJrKrLrErrrzrwrrr=rrrrrrrs    rc Cszyddlj}Wn,tk r:}ztd|WYdd}~XnX|rJt|}nd}|j|||||j|d}|j|\} } } | S)Nrzoauth support is not available)Z client_secretZresource_owner_keyZresource_owner_secretZsignature_methodr)Zoauthlib.oauth1oauth1 ImportErrorNotImplementedErrorr"ZClientZSIGNATURE_PLAINTEXTZsign) rrrrrrrr@ZclientZ_uriZsigned_headersZ_bodyrrrr&s  r)r(r))NNrrNNNNTTNNFTrF)N)rr)N)=rprZloggingrrruconcurrent.futuresrrrZ email.utilsrr;r functoolsrZ http.clientr itertoolsr Ztypingr r r r rrrZ urllib.parserrrrWrZ cloudinitrZ getLoggerrJr5rrr'rArBr(r)r:r<r]r[r=r"rZrrmrrrrrrrrrrr s~     $    1 (P8F|