tPc@sdZddlZddlZddlZddlZddlZdaddlZej dkrlda nda de fdYZ d e fd YZ d e ejfd YZd ejfdYZdZdZdejfdYZdZdadZdZddZdZddZedkrddlZddlZy$eejdZejdZWn'e e!fk rdejdGHqXeeendS(s An HTTP handler for urllib2 that supports HTTP 1.1 and keepalive. >>> import urllib2 >>> from keepalive import HTTPHandler >>> keepalive_handler = HTTPHandler() >>> opener = urllib2.build_opener(keepalive_handler) >>> urllib2.install_opener(opener) >>> >>> fo = urllib2.urlopen('http://www.python.org') If a connection to a given host is requested, and all of the existing connections are still in use, another connection will be opened. If the handler tries to use an existing connection but it fails in some way, it will be closed and removed from the pool. To remove the handler, simply re-run build_opener with no arguments, and install that opener. You can explicitly close connections by using the close_connection() method of the returned file-like object (described below) or you can use the handler methods: close_connection(host) close_all() open_connections() NOTE: using the close_connection and close_all methods of the handler should be done with care when using multiple threads. * there is nothing that prevents another thread from creating new connections immediately after connections are closed * no checks are done to prevent in-use connections from being closed >>> keepalive_handler.close_all() EXTRA ATTRIBUTES AND METHODS Upon a status of 200, the object returned has a few additional attributes and methods, which should not be used if you want to remain consistent with the normal urllib2-returned objects: close_connection() - close the connection to the host readlines() - you know, readlines() status - the return status (i.e. 404) reason - english translation of status (i.e. 'File not found') If you want the best of both worlds, use this inside an AttributeError-catching try: >>> try: status = fo.status >>> except AttributeError: status = None Unfortunately, these are ONLY there if status == 200, so it's not easy to distinguish between non-200 responses. The reason is that urllib2 tries to do clever things with error codes 301, 302, 401, and 407, and it wraps the object upon return. For python versions earlier than 2.4, you can avoid this fancy error handling by setting the module-level global HANDLE_ERRORS to zero. You see, prior to 2.4, it's the HTTP Handler's job to determine what to handle specially, and what to just pass up. HANDLE_ERRORS == 0 means "pass everything up". In python 2.4, however, this job no longer belongs to the HTTP Handler and is now done by a NEW handler, HTTPErrorProcessor. Here's the bottom line: python version < 2.4 HANDLE_ERRORS == 1 (default) pass up 200, treat the rest as errors HANDLE_ERRORS == 0 pass everything up, error processing is left to the calling code python version >= 2.4 HANDLE_ERRORS == 1 pass up 200, treat the rest as errors HANDLE_ERRORS == 0 (default) pass everything up, let the other handlers (specifically, HTTPErrorProcessor) decide what to do In practice, setting the variable either way makes little difference in python 2.4, so for the most consistent behavior across versions, you probably just want to use the defaults, which will give you exceptions on errors. iNiiiitConnectionManagercBsGeZdZdZdZdZdZdZddZ RS(sV The connection manager must be able to: * keep track of all existing cCs.tj|_i|_i|_i|_dS(N(tthreadt allocate_lockt_lockt_hostmapt_connmapt _readymap(tself((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt__init__s  cCss|jjzQ||jkr/g|j| host is the host:port spec, as in 'www.cnn.com:8080' as passed in. no error occurs if there is no connection to that host.N(RRRtclose(RR th((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytclose_connectionscCsUxN|jjjD]7\}}x(|D] }|jj||jq)WqWdS(sclose all open connectionsN(RRt iteritemsRR$(RR tconnsR%((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt close_alls" cCs|jj|ddS(setells us that this request is now closed and that the connection is ready for another requestiN(RR(RtrequestR R ((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt_request_closedsicCs'|r|jn|jj|dS(N(R$RR(RR R R$((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt_remove_connections cCs|jt|S(N(tdo_opentHTTPConnection(Rtreq((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt http_openscCs|j}|s$tjdny|jj|}x|r|j|||}|raPn|j|jj||jj|}q<W||}trtj d|t |n|jj ||d|j |||j }Wn.tjtjfk r"}tj|nX|jr?|jj|ntratj d|j|jn||_||_|j|_||_|j|_|j|_|j|_|jdkst r|S|jjd|||j|j|jSdS(Ns no host givens"creating new connection to %s (%d)isSTATUS: %s, %sithttp(tget_hostturllib2tURLErrorRRt_reuse_connectionR$RtDEBUGtinfotidRt_start_transactiont getresponsetsocketterrorthttplibt HTTPExceptiont will_closetstatustreasont_handlert_hostt get_full_urlt_urlt _connectiontcodetmsgtheaderst HANDLE_ERRORStparent(Rt http_classR/R R%trterr((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR-sH            cCsy |j|||j}Wnhtjtjfk rEd}nFtrjtjd|t|n|j j ||j nX|dks|j dkrtrtj d|t|nd}n"trtj d|t|n|S(sGstart the transaction with a re-used connection return a response object (r) upon success or None on failure. This DOES not close or remove bad connections in cases where it returns. However, if an unexpected exception occurs, it will close and remove the connection before re-raising. s4unexpected exception - closing connection to %s (%d)i s&failed to re-use connection to %s (%d)sre-using connection to %s (%d)N(R9R:R;R<R=R>RR6R8RRR$tversionR7(RR%R/R RM((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR5s(      c Cs|jj}tjdkr1|j|jn|j|jjtd|j D}i}x7dD]/}||krmd|d|j dd LsR saccept-encodingitskip_t-t_tPOSTs content-types Content-types!application/x-www-form-urlencodedscontent-lengthsContent-lengths%dtGET(ii(shostsaccept-encoding(RItcopytsyst version_infotupdatetunredirected_hdrsRKt addheadersRR treplacethas_datatget_datat putrequestt get_selectort putheaderR!R;R<R3R4t endheaderstsend( RR%R/RIt skipheadersRRtdataRNtkRS((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR9Es4  !         ( RRRR#R&R)R+R,R0R-R5R9(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRs        4 .t HTTPHandlercBseZRS((RR(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRjdst HTTPResponsecBsweZddd dZejjZdZdZ dZ dZ d dZdZ dd Z dd ZRS( icCshtjj|||||j|_d|_d|_d|_d|_d|_ d|_ d|_ dS(Nti( R=RkRtfilenoRRGt_rbuft _rbufsizeRBRCRERF(Rtsockt debugleveltstricttmethod((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR{s       cCsN|jrJ|jjd|_|jrJ|jj||j|jqJndS(N(tfpR$RRBR+RCRF(R((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR$s     cCs-|jj|j|jdd|jdS(NR$i(RBR,RCRFR$(R((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR&scCs|jS(N(RI(R((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR7scCs|jS(N(RE(R((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytgeturlscCs|jra|dk rat|j}||kr=||8}qa|j| }|j||_|Sn|j|j|}d|_|S(NRl(RnRR!t _raw_read(RtamttLts((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytreads    cCs|j}d}x[trl|dkr|jj}|jd}|dkr[|| }nyt|d}Wn*tk r|jt j |nX|dkrPqn|dkr||j |7}n||kr||j |7}|||_|S||kr9||j |7}|j dd|_|S||j |7}||8}|j dd}qWx3tr|jj}|sPn|dkrpPqpqpW|j|S(NRlt;iiis ( t chunk_lefttTrueRRttreadlinetfindtintt ValueErrorR$R=tIncompleteReadt _safe_read(RRwR|tvaluetlineti((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt _read_chunkedsL                    icCs |jjd}x|dkrd|koAt|jkn r|j|j}|scPn|jd}|dkr|t|j}n|j||_qW|dkrt|j}n |d}d|kot|jknr|}n|j| |j|}|_|S(Ns ii(RnRR!RvRo(RtlimitRtnewRh((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR~s 5   % cCsfd}g}xStra|j}|s+Pn|j||t|7}|r||krPqqW|S(Ni(R}R~R R!(RtsizehintttotalRR((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt readliness   N(RRRRR=RkRzRvR$R&R7RuRR~R(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRkgs       8 cCswt|dddk rdS|jdkrM|jrA|jqMtjn|jdkrndGt|GHnyd}t|dd}|dk r|jdkrdGHn||}x9|r|jj |||}qWn|jj |Wn{t j k rr}t }|dt jkrc|jtjkrVd|_|j|_t}n|jn|rsqsnXdS(s`Send `str' to the server. Shamelessly ripped off from httplib to patch a bad behavior. t_broken_pipe_respNissend:i Rzssending a read()able(tgetattrRRpt auto_opentconnectR=t NotConnectedRqtreprtsendallR;R<R}terrnotEPIPEt_HTTPConnection__statet _CS_REQ_SENTRR:tFalseR$(Rtstrt blocksizeRzRhRStreraise((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytsafesends:          cs"fd}jj|_|S(s>Wraps getresponse in cls with a broken-pipe sane version. cs/t|dd}|dk r"|Sj|S(NR(RRR:(RRM(tcls(s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytsafegetresponse9s (R:R(RR((Rs7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytwrapgetresponse6s R.cBs#eZeZeZeejZ RS(( RRRktresponse_classRRfRR=R.R:(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyR.Esc Cs!t}t}tj|}tj|idd6dd6}xd D]}d|||fGH|ay^tj|}|j|jy|j|j }}Wnt k rd \}}nXWnt k r} d| GHqFXd||fGHqFW|a|j } dG| GH|jdS( Ntoffitonis. fancy error handling %s (HANDLE_ERRORS = %i)s EXCEPTION: %ss status = %s, reason = %ssopen connections:(ii(NN(RJRjR3t build_openertinstall_openerturlopenRzR$R@RAtAttributeErrorRtIOErrorR#R)( turltorigtkeepalive_handlertopenertposRtfoR@RAtethosts((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt error_handlerPs0         cCsHyddlm}Wn!tk r7ddlm}nX|a||S(Ni(tmd5(thashlibRt ImportError(Ryt_md5((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRls  cCsDd}tj}tj|tj|}|j}|jtj|}|d|jfGHtjt }tj|tj|}|j}|jtj|}|d|jfGHtj|}d}x*t r|j }|r ||}qPqW|jtj|}|d|jfGHdS(Ns%25s: %ss normal urllibskeepalive readRlskeepalive readline( R3RRRRzR$RRt hexdigestRjR}R~(RtformatRRtfootmtf((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt continuityus2           cCsd||fGHtjjdtj}tj|t||}d|GHtjjdtjt}tj|t||}d|GHd||GHdS(Ns making %i connections to: %ss( first using the normal urllib handlerss TIME: %.3f ss( now using the keepalive handler s improvement factor: %.2f(RZtstdouttwriteR3RRtfetchRj(tNRRtt1tt2((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytcomps     c Csddl}g}|j}xnt|D]`}|rS|dkrS|j|ntj|}|j}|j|jt|q+W|j|} d} x>|dD]2}| d} ||dksd| |fGHqqW| S(Niiis+WARNING: inconsistent length on read %i: %i( ttimetrangetsleepR3RRzR$R R!( RRtdelayRtlenst starttimeRRRtdifftj((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRs"     cCst}dtfdY}|adGHtj|}|j}|jd}d|GHxH|dkrtjjd|tjj t j d|d8}qaWtj jd d GHtj|}|j}|j||krd GHnd GH|adS( Nt FakeLoggercBseZdZeZZZRS(cWs ||GHdS(N((RRHtargs((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytdebugs(RRRR7twarningR<(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyRs s- fetching the file to establish a connectionis; waiting %i seconds for the server to close the connectionis %2iis s! fetching the file a second times data are identicals ERROR: DATA DIFFER( R6tobjectR3RRzR$RZRRtflushRRtstderr(RtdbbackupRRtdata1Rtdata2((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyt test_timeouts.         i cCsmdGHyt|Wn tk r5dGHtjnXHdGHt|HdGHt||HdGHt|dS(Ns-checking error handler (do this on a non-200)s.exiting - exception will prevent further testss>performing continuity test (making sure stuff isn't corrupted)sperforming speed comparisons#performing dropped-connection check(RRRZtexitRRR(RR((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pyttests   t__main__s%s (ii("RRR=R;RR3RR6RZR[RJRRRRjRkRRR.RRRRRRRRRRtargvRRt IndexErrorR(((s7/sys/lib/python2.7/site-packages/mercurial/keepalive.pytlsB       ? 3   !   #