
    	^c8?                        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ZddlmZ ddl	m
Z
mZmZmZ d Zd Zd Z G d d	          Zej        sej        r
d
Zej        ZndZdZddZ	 	 	 ddZddZd ZddZej        reZneZeZd ZdS )    N   )_)encodingerrorpycompatscmutilc                  
   	 t          t          j        d                    } | dk    r| S n# t          t          f$ r Y nw xY w	 t          t
          j        d                   } | dk    r| S n# t          t          f$ r Y nw xY wdS )z-try to count the number of CPUs on the systemSC_NPROCESSORS_ONLNr   s   NUMBER_OF_PROCESSORSr   )intossysconfAttributeError
ValueErrorr   environKeyError)ns    2/usr/lib/python3/dist-packages/mercurial/worker.py	countcpusr      s    
01122q55H J'    !89::q55H j!    1s    (, A A &A, ,B ?B c                    |                      dd          }|rH	 t          |          }|dk    r|S n/# t          $ r" t          j        t          d                    w xY wt          t          t                      d          d          S )N   workers   numcpusr   s!   number of cpus must be an integer       )	configr   r   r   Abortr   minmaxr   )uisr   s      r   _numworkersr   0   s    
		)Z((A G	GAAAvv  	G 	G 	G+a DEEFFF	Gs9;;""B'''s	   2 ,Ac                  R    t          j                    t          j                    k    S N)	threadingcurrent_threadmain_thread     r   ismainthreadr'   <   s    #%%)>)@)@@@r&   c                   ,    e Zd ZdZd Zd Zd ZddZdS )	_blockingreadera  Wrap unbuffered stream such that pickle.load() works with it.

    pickle.load() expects that calls to read() and readinto() read as many
    bytes as requested. On EOF, it is fine to read fewer bytes. In this case,
    pickle.load() raises an EOFError.
    c                     || _         d S r!   )_wrapped)selfwrappeds     r   __init__z_blockingreader.__init__H   s    r&   c                 4    | j                                         S r!   )r+   readliner,   s    r   r0   z_blockingreader.readlineK   s    }%%'''r&   c                    d}t          |          }t          |          5 }||k     rJ||d          5 }| j                            |          }d d d            n# 1 swxY w Y   |sn||z  }||k     Jd d d            n# 1 swxY w Y   |S Nr   )len
memoryviewr+   readinto)r,   bufpossizeviewsubviewrets          r   r6   z_blockingreader.readintoN   s   3xx__ 	**#$$Z :7-0099C: : : : : : : : : : : : : : : s
 **	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
s4   A>AA>A	A> A	!A>>BBc                     |dk     r| j                                         S t          |          }|                     |          }||d = t	          |          S r3   )r+   readall	bytearrayr6   bytes)r,   r9   r7   n_reads       r   readz_blockingreader.read]   sR    !88=((***oos##LSzzr&   N)r=   )__name__
__module____qualname____doc__r.   r0   r6   rC   r%   r&   r   r)   r)   @   s_              ( ( (       r&   r)   g{Gz?gꌠ9Y>)FFTc                 r    |s	t           rdS ||z  }t          |           }|t          |z  ||z  z   z
  }|dk    S )zetry to determine whether the benefit of multiple processes can
    outweigh the cost of starting themFg333333?)_DISALLOW_THREAD_UNSAFEr   _STARTUP_COST)r   	costperopnops
threadsafelinearworkersbenefits          r   
worthwhilerQ   r   sQ      1 uF"ooG/&72BBCGd?r&   c                     |                      dd          }|rt          t          u rt                      sd}|r5t	          | |t          |          |          rt          | |||||          S  |||fz    S )a  run a function, possibly in parallel in multiple worker
    processes.

    returns a progress iterator

    costperarg - cost of a single task

    func - function to run. It is expected to return a progress iterator.

    staticargs - arguments to pass to every invocation of the function

    args - arguments to split into chunks, to pass to individual
    workers

    hasretval - when True, func and the current function return an progress
    iterator then a dict (encoded as an iterator that yield many (False, ..)
    then a (True, dict)). The dicts are joined in some arbitrary order, so
    overlapping keys are a bad idea.

    threadsafe - whether work items are thread safe and can be executed using
    a thread-based worker. Should be disabled for CPU heavy tasks that don't
    release the GIL.

    prefork - a parameterless Callable that is invoked prior to forking the
    process.  fork() is only used on non-Windows platforms, but is also not
    called on POSIX platforms if the work amount doesn't warrant a worker.
    r   s   enabledF)rM   )prefork)
configbool_platformworker_posixworkerr'   rQ   r4   )	r   
costperargfunc
staticargsargs	hasretvalrM   rS   enableds	            r   workerr]      s    J mmIz22G ?l22<>>2  
:b*c$iiJOOO 
j$	7
 
 
 	
 4tg%&&r&   c           	   #   n	  K   t          |           }t          j        t          j                  t          j        t          j        t          j                   t                      dgcfddfd	fd}t          j        t          j        |          |                                  t          j	                    }g i }	|r
 |             t          |t          |t          |                              D ]t          j                    \                      f           d}
	 t          j                    }|dk    r]t          j        t          j                   t          j        t          j                   fd}t!          j        | |          }
nd#  t          j	                    |k    r t%          j                    d         }t)          |t*                     }|                     |           Y nxY wt          j	                    |k    rQ	 |                                  n#  Y nxY wt          j        |
d	z             n# t          j        |
d	z             w xY wnm# t          j	                    |k    rQ	 |                                  n#  Y nxY wt          j        |
d	z             w # t          j        |
d	z             w xY ww xY w                    |           t3          j                    D ]M\  t          j                                       t          j        d
d          t2          j                   Nfd}	 t                    }|dk    r                                D ]\  }}	 tA          j!        tE          |j#                            }|r$|d         r|	$                    |d                    n|V  W# tJ          $ r; &                    |j#                   |j#                                         |dz  }Y w xY w|dk    n#                 |              xY w |            }|rA|dk     r't          j'        t          j	                    |            tQ          j)        |          |rd|	fV  d S d S )Nr   c                      t          j         t           j                   D ]2} 	 t          j        | t           j                   ## t
          $ r Y /w xY wd S r!   )signalSIGCHLDr   killSIGTERMProcessLookupError)poldchldhandlerpidss    r   killworkersz!_posixworker.<locals>.killworkers   sn     	fnn555 	 	A6>****%   	 	s   A
AATc                 D                                    D ]}dx}}	 t          j        || rdnt          j                  \  }}n%# t          $ r                     |           Y nw xY w|sV                    |           t          |          }|rd         s|d<   d S r3   )copyr   waitpidWNOHANGChildProcessErrordiscard_exitstatus)blockingpidre   strg   problems       r   waitforworkersz$_posixworker.<locals>.waitforworkers   s    99;; 	  	 CJA"
3h)FBJHH22$ " " " S!!!!!"   LLOOORB  '!*  
	  	 s   &AA&%A&c                 H     d           d         r              d S d S )NF)rp   r   r%   )signumframerh   rs   rt   s     r   sigchldhandlerz$_posixworker.<locals>.sigchldhandler   s;    &&&&1: 	KMMMMM	 	r&   r=   c                  f   d d         D ]-\  } }t          j        |            t          j        |           .t          j                   t          j        	d          5 } fz    D ]+}t          j        ||           |                                 ,	 d d d            n# 1 swxY w Y   dS )Nr=   wbr   )r   closefdopenpickledumpflush)
rwwfresultrX   pargspipesrfdrY   wfds
       r   
workerfuncz _posixworker.<locals>.workerfunc   s     %crc
 $ $1HSMMM3-- '&*dZ5(-B&D ' 'F"K333HHJJJJ'' ' ' ' ' ' ' ' ' ' ' ' ' ' ' 1s   #6B&&B*-B*)force   rbc                      t          j         t           j                                 t          j         t           j                                                     d         S r3   )r`   SIGINTra   r{   )rf   
oldhandlerrs   selectorrt   s   r   cleanupz_posixworker.<locals>.cleanup  sS    fmZ000fnn555qzr&   r   T)*r   r`   	getsignalr   SIG_IGNsetra   r   r   getpid	partitionr   r4   pipeappendforkr   	callcatchsysexc_info
issubclassKeyboardInterrupt	traceback_exitadd	selectorsDefaultSelectorr{   registerr|   
EVENT_READselectr}   loadr)   fileobjupdateEOFError
unregisterrb   r   WorkerError) r   rX   rY   rZ   r[   rS   rO   rx   	parentpidretvalr<   rq   r   exctyper   r   	openpipeskeyeventsresstatusrh   rf   r   r   rg   r   rs   r   r   rt   r   s     ``                  @@@@@@@@@@@r   rV   rV      s*     "ooG!&-00J
M&-000EEA3MD'
 
 
 
 
 
             $      
 ]6>>BBNHHJJJ	IEF 			4Wc$ii!8!899 0 0 799Sc3Z    	('))CaxxfmZ888fnn===	 	 	 	 	 	 	 	 	 	 'J77	&y{{i''lnnQ'G"7,=>>>ELLuL%%%%%y{{i''(HHJJJJDHS3Y''''BHS3Y'''' (ry{{i''(HHJJJJDHS3Y''''BHS3Y'''' ( 	(**H I IS

 	")Cq1193GHHHH        JJ	!mm'00 # #V# !+ock&B&BCCC  "SV "c!f----!			 # # #''444K%%'''NIII# !mm$			WYYF (A::GBIKK&)))''' Fl s    A6F76J7AHJ3II'I
I''J K.J21K2J6	4K9K.K*	*K.5.Q $AO54Q 5AP:7Q 9P::	Q Qc                     t          j        |           rt          j        |           S t          j        |           rt          j        |            S dS )zconvert a posix exit status into the same form returned by
    os.spawnv

    returns None if the process was stopped instead of exitingN)r   	WIFEXITEDWEXITSTATUSWIFSIGNALEDWTERMSIG)codes    r   _posixexitstatusr   E  sU    
 
|D $~d###			 $T""##$ $r&   c              #      K    G d dt           j                  }g  fd}t                     }t          j                                        }	t          j                                        }
i }t          ||dz            D ]}|
                    |           t          |          D ]9} ||
|	||          }	                    |           |
                                 :	 t                    dk    r|	                                sR|	                                }|r$|d         r|                    |d                    n|V  |	                                Rd                             d           d D             }|D ]%}|j        |j                            |           &t                    dk    n # t$          t&          f$ r  |              w xY w|	                                sR|	                                }|r$|d         r|                    |d                    n|V  |	                                R|rd	|fV  d S d S )
Nc                        e Zd Zd Zd Zd ZdS )_windowsworker.<locals>.Workerc                     t          j        j        | g|R i | || _        || _        || _        || _        d| _        d| _        d | _	        d S )NFT)
r"   Threadr.   
_taskqueue_resultqueue_func_staticargs_interrupteddaemon	exception)r,   	taskqueueresultqueuerX   rY   rZ   kwargss          r   r.   z'_windowsworker.<locals>.Worker.__init__R  s`     %d<T<<<V<<<'DO +DDJ)D %DDK!DNNNr&   c                     d| _         d S )NT)r   r1   s    r   	interruptz(_windowsworker.<locals>.Worker.interrupt^  s     $Dr&   c                    	 | j                                         s	 | j                                         } | j        | j        |fz    D ]&}| j                            |           | j        r d S 'n# t          j	        j
        $ r Y d S w xY w| j                                         d S d S # t          $ r}|| _         d }~ww xY wr!   )r   empty
get_nowaitr   r   r   putr   r   queueEmpty	Exceptionr   )r,   rZ   r   es       r   runz"_windowsworker.<locals>.Worker.runa  s   ///11 
#99;;#-4:t/?4'/I#J ' 'C -11#666  $0 ' &'' $>/    ///11          "#	sA   B( AA0 .A0 /B( 0BB( BB( (
B?2B::B?N)rD   rE   rF   r.   r   r   r%   r&   r   Workerr   Q  sA        
	" 
	" 
	"	% 	% 	%	 	 	 	 	r&   r   c                  8   t          j                     dz   } D ]}|                                 D ]f}| t          j                     z
  }|                    |           |                                r%                    t          d                      d S gd S )Nr   s:   failed to kill worker threads while handling an exception
)timer   joinis_alivewarnr   )
cleanupendtremainingtimethreadsr   s      r   trykillworkersz&_windowsworker.<locals>.trykillworkersw  s    Y[[1_
 	 	AKKMMMM 	 	A&4MFF=!!!zz|| 
 3    	 	r&      r   r   g?c                 :    g | ]}|                                 |S r%   )r   ).0_ts     r   
<listcomp>z"_windowsworker.<locals>.<listcomp>  s%    IIIb2;;==IrIIIr&   T)r"   r   r   r   r   Queuer   r   ranger   startr4   r   getr   r   r   remover   r   )r   rX   rY   rZ   r[   rS   r   r   rO   r   r   r   r   _ir   r   finishedthreadsr   s   `                @r   _windowsworkerr   P  s     " " " " "! " " "H G     * "ooG.&&((K$$&&IF 42..  eGnn  F9k4<<q					'llQ!'')) !oo'' Q MM#a&))))III "''))  AJOOD!!!IIGIIIO$ " ";*+%q!!!! 'llQ ()    !! oo 	Q 	MM#a&!!!!III !!   Fl s   'CG G c              #   H   K   t          |          D ]}| |d|         V  dS )a  partition a list into N slices of roughly equal size

    The current strategy takes every Nth element from the input. If
    we ever write workers that need to preserve grouping in input
    we should consider allowing callers to specify a partition strategy.

    olivia is not a fan of this partitioning strategy when files are involved.
    In his words:

        Single-threaded Mercurial makes a point of creating and visiting
        files in a fixed order (alphabetical). When creating files in order,
        a typical filesystem is likely to allocate them on nearby regions on
        disk. Thus, when revisiting in the same order, locality is maximized
        and various forms of OS and disk-level caching and read-ahead get a
        chance to work.

        This effect can be quite significant on spinning disks. I discovered it
        circa Mercurial v0.4 when revlogs were named by hashes of filenames.
        Tarring a repo and copying it to another disk effectively randomized
        the revlog ordering on disk by sorting the revlogs by hash and suddenly
        performance of my kernel checkout benchmark dropped by ~10x because the
        "working set" of sectors visited no longer fit in the drive's cache and
        the workload switched from streaming to random I/O.

        What we should really be doing is have workers read filenames from a
        ordered queue. This preserves locality and also keeps any worker from
        getting more than one file out of balance.
    N)r   )lstnslicesis      r   r   r     s@      : 7^^  !*W*o r&   r   )FTNr!   )r   r}   r   r`   r   r"   r   i18nr    r   r   r   r   r   r   r'   r)   isposix	iswindowsrJ   rI   rQ   r]   rV   r   r   rU   ro   r   r%   r&   r   <module>r      s   
			       



                        ,	( 	( 	(A A A$ $ $ $ $ $ $ $N  $x) $M '0M#
 
 
 
& /' /' /' /'dQ Q Q Qh$ $ $` ` ` `F  #$OO"O"K    r&   