gf> dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlZddlmZddlmZddlmZddlZddlmZddlmZdd lmZdd lm Z dd lm!Z!dd lm"Z"dd lm#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl(m)Z)ddl(m*Z*ddl(m+Z+ddl(m,Z,ddl(m-Z-ddl(m.Z.ddl(m/Z/ddl(m0Z0e+rddl1Z1nddl2Z1 ddl1m3Z3nF#e4$r>ej55ej6dddl3Z3dddn #1swxYwYYnwxYwej7dkrddl8Z8ndZ8gdZ9dej:vZ;de j<vZ=de j<vpd e j<vZ>e=pe>Z?ej@d!kZAd"ZBd#ZCd$ZDd%ZEe?reBd&zZBeEd&zZEeCd&zZCeDd&zZDe jFd'krd(e jGzZHnd)e jGzZHe.d*ZIe+rd+Jd,d-ZKnd.ZKejLMd/vZNe jOPe jOQe jOReSd0d0ZTe jOQeTd1ZUe jOPe jOReSZVe!oe" ZWeXejYd2ZZeXed3Z[eXed4Z\eXejYd5Z]eXejYd6Z^eXejYd7Z_eXed8Z`eXejYd9ZaeXejYd:ZbeXejYd;ZceXed<Zd edoeeejfZgn #eh$rd=ZgYnwxYweXed>ZieXed?ZjeXejYd@Zke seoe jldkZmdAZnenZoepe jqdBZrejserjtdCeueDZvewedDexZyezZ{ezZ|GdEdFej}Z~dGZeddHZedIZdJZedKZedLZejeEfdMZddNZdOZdPZGdQdRexZeejdeEdSTdUZee*efdeEdSTddWZeedeEdSTdXZdYZdZZejd[Zdd\Zdd^ZGd_d`e1jZee1_GdadbeZe1je;dcGdddeeZdfZdgZGdhdiZGdjdkZdlZeBfdmZddnZddoZddqZeedfdrZejfdsZdduZdvZejdwZdxZdyZdzZd{Zd|Zd}Ze!rejdd~ZnejddZejsdZe!rejejddSdS)z Test utilities. )print_functionN)AF_INET)AF_INET6) SOCK_STREAM)AIX)FREEBSD)LINUX)MACOS)POSIX)SUNOS)WINDOWS) bytes2human) print_color) supports_ipv6)FileExistsError)FileNotFoundError)PY3)range)super)u)unicode)which)mockignore)EAPPVEYORDEVNULLGLOBAL_TIMEOUTTOLERANCE_SYS_MEM NO_RETRIESPYPY PYTHON_EXEROOT_DIR SCRIPTS_DIR TESTFN_PREFIXUNICODE_SUFFIXINVALID_UNICODE_SUFFIX CI_TESTINGVALID_PROC_STATUSESTOLERANCE_DISK_USAGEIS_64BITHAS_CPU_AFFINITY HAS_CPU_FREQ HAS_ENVIRONHAS_PROC_IO_COUNTERS HAS_IONICEHAS_MEMORY_MAPSHAS_PROC_CPU_NUM HAS_RLIMITHAS_SENSORS_BATTERY HAS_BATTERYHAS_SENSORS_FANSHAS_SENSORS_TEMPERATURESHAS_MEMORY_FULL_INFOpyrun terminate reap_childrenspawn_testproc spawn_zombiespawn_children_pairThreadTaskunittestskip_on_access_deniedskip_on_not_implementedretry_on_failureTestMemoryLeakPsutilTestCaseprocess_namespacesystem_namespace print_sysinfo install_pipinstall_test_depschdir safe_rmpath create_exe decode_path encode_path get_testfn get_winverkernel_version call_until wait_for_pid wait_for_filecheck_net_address get_free_port bind_socketbind_unix_sockettcp_socketpairunix_socketpaircreate_sockets reload_moduleimport_module_by_pathwarncopyload_shared_lib is_namedtuple__pypy__rGITHUB_ACTIONS CIBUILDWHEELl iPirjavaz $psutil-%s-z @psutil-%s-u-ƒőősfutf8surrogateescapeufÀ€)asciizus-asciiz..scripts cpu_affinitycpu_freq getloadavgenvironionice memory_mapsnet_io_counterscpu_num io_countersrlimitsensors_batteryF sensors_fanssensors_temperaturesthreadsc d}trktr%trtdntdStr)t jtj StdStr|tj p|t jtj pZ|tdtj ddzp-|tj }|std|St jtj }t j|s J||S)Nc tj|dgtjtj|S#t$rYdSwxYw)Nz-V)stdoutstderr) subprocess check_callPIPE Exception)exes w/builddir/build/BUILD/imunify360-venv-2.3.5/opt/imunify360/venv/lib64/python3.11/site-packages/psutil/tests/__init__.pyattemptz_get_py_exe..attempts_   !d JOJO M M M M J   44 s -1 ??pypy3pypypythonz python%s.%sz"can't find python exe real abspath)rdr#rrrospathrealpathsys executabler version_infopsutilProcessr ValueErrorexists)rrs r _get_py_exersZ  #%(;5>>>eFmm ;  #7##CN33 3?? "   GCN # # , GBG$$S^44 5 5 , GE-#*:2A2*>>?? @ @ , GFN$$((** + +  CABB B gs~..w~~c""''C''" zr+cbg|],}|dtt|-S)STATUS_ startswithgetattrr.0xs r rsB333a,,y113wvq))333rAF_UNIXcFeZdZdZfdZdZdZdZdZdZ dZ xZ S) ThreadTaskz6A thread task which does nothing expect staying alive.ctd|_d|_t j|_dS)NFMbP?)r__init___running _interval threadingEvent_flag)self __class__s rrzThreadTask.__init__s:  _&& rcN|jj}d||jt|fzS)Nz<%s running=%s at %#x>)r__name__rid)rnames r__repr__zThreadTask.__repr__s&~&'44*IIIrc.||SN)startrs r __enter__zThreadTask.__enter__s  rc.|dSr)stop)rargskwargss r__exit__zThreadTask.__exit__s rc|jrtdtj||jdS)zStart thread and keep it running until an explicit stop() request. Polls for shutdown every 'timeout' seconds. zalready startedN)rrrThreadrrwaitrs rrzThreadTask.startsL = 0.// /t$$$ rcd|_|j|jr"tj|j|j dSdS)NT)rrsettimesleeprrs rrunzThreadTask.runsW  m ' Jt~ & & &m ' ' ' ' 'rch|jstdd|_|dS)z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)rrjoinrs rrzThreadTask.stops3} 0.// /  r) r __module__ __qualname____doc__rrrrrrr __classcell__)rs@rrrs@@''''' JJJ''' rrcFtjfd}|S)NcP |i|S#t$rtwxYwr)rr=)rrfuns rwrapperz&_reap_children_on_err..wrapper%sD 3''' '    OOO  s % functoolswraps)rrs` r_reap_children_on_errr$s8_S Nrc |dt|dt|dtj|dtjt rd}|d||t } t|d|z}td |g}tj |fi|}t |t|d d t|nT#t|wxYwtj |fi|}t |t|j|S) a}Creates a python subprocess which does nothing for 60 secs and return it as a subprocess.Popen instance. If "cmd" is specified that is used instead of python. By default stdin and stdout are redirected to /dev/null. It also attemps to make sure the process is in a reasonably initialized state. The process is registered for cleanup on reap_children(). stdinr}cwdenv creationflagsNz:from time import sleep;open(r'%s', 'w').close();sleep(60);z-cTdeleteempty) setdefaultrrgetcwdrpr rQrMr$rPopen_subprocesses_startedaddrVrUpid)cmdkwdsCREATE_NO_WINDOWtestfnpylinesprocs rr>r>/sf OOGW%%%OOHg&&&OOE29;;'''OOE2:&&&;% )9::: {    "$*+FtV,C$S11D11E ! % %e , , , &T : : : :     K     ----!!%(((UY Ls .ADD+cd}ttj} tjdtj|dtd}trt|d\}}nt|\}}tj |j }tt|dd }t|tj |}||ft#||t#|SS#t#||t#|wwxYw) aCreate a subprocess which creates another one as in: A (us) -> B (child) -> C (grandchild). Return a (child, grandchild) tuple. The 2 processes are fully initialized and will live for 60 secs and are registered for cleanup on reap_children(). Ndirzl import subprocess, os, sys, time s = "import os, time;" s += "f = open('z', 'w');" s += "f.write(str(os.getpid()));" s += "f.close();" s += "time.sleep(60);" p = subprocess.Popen([r'z.', '-c', s]) p.wait() r)rTFr)rQrrtextwrapdedentrbasenamer$r r;rrrintrV _pids_startedrrM)tfilerssubpchildgrandchild_pid grandchilds rr@r@Ws@ E BIKK ( ( (F OO7##F++++ZZZ 9 : :  #333KD%%((KD%tx((]6$eLLLMM.)))^N33 z"F         F        s CD#D>cztjsJt}tjd|z}d}t |} |tt|\}}| \}} tj | gggtt| d}t|tj|t#fdd|f||t'||t'|SS#|wxYw#|t'||t'|wwxYw)zCreate a zombie process and return a (parent, zombie) process tuple. In order to kill the zombie parent must be terminate()d first, then zombie must be wait()ed on. a import os, sys, time, socket, contextlib child_pid = os.fork() if child_pid > 0: time.sleep(3000) else: # this is the zombie process s = socket.socket(socket.AF_UNIX) with contextlib.closing(s): s.connect('%s') if sys.version_info < (3, ): pid = str(os.getpid()) else: pid = bytes(str(os.getpid()), 'ascii') s.sendall(pid) Nc,Sr)status)zombiesrzspawn_zombie..sv}}rzret == psutil.STATUS_ZOMBIE)rr rQrrrZ settimeoutr r;acceptselectfilenorrecvrrrrTcloserM) unix_filesrcrsockparentconn_zpidrs @rr?r?~s << I /   C E I & &D '''c ++--a  M4;;==/2r> B B Btyy''D   d # # #^D))F ....0M N N NF# JJLLL I         JJLLLL I        s&AF BE* F*FF7F:c |dd|ddt} t|d5}||dddn #1swxYwYt t |jgfi|}t|j||fS#t$rt|wxYw)zRun python 'src' code string in a separate interpreter. Returns a subprocess.Popen instance and the test file where the source code was written. r}Nr~wt) rrQopenwriter>r$rrUrrrM)rrsrcfilefrs rr;r;s   OOHd###OOHd###llG '4  A GGCLLL               z162;;d;;TXg G s/B* A." B*.A22B*5A263B**Cc t|ttfrdnd}tr|rdnd}|d||dt j|dt j|dd|d |t j|fi|}t |tr| t \}}n| \}}|j dkrt||rt||d r |d d }|S)zUrun cmd in a subprocess and return its output. raises RuntimeError on error. TFrrshellr}r~universal_newlinesrtimeout N) isinstancestrrr rrrrrrr communicater returncode RuntimeErrorr`endswith)rrrflagspr}r~s rshrsN sS'N33 >DDE 1U 1IIEOOGU###OOHjo...OOHjo...OO($///OOOU+++%%%%Aa    )~>>|q6"""  V  t Mrc trddlm d d fd} fd fd}d}|} t|try|||t|t jtjfr ||t|tr|n|j}tj |r J|St|tj tjfry ||t|t jtjfr ||t|tr|n|j}tj |r J|St|t jry|||t|t jtjfr ||t|tr|n|j}tj |r J|Std |z#t|t jtjfr ||t|tr|n|j}tj |r J|wxYw) aTerminate a process and wait() for it. Process can be a PID or an instance of psutil.Process(), subprocess.Popen() or psutil.Popen(). If it's a subprocess.Popen() or psutil.Popen() instance also closes its stdin / stdout / stderr fds. PID is wait()ed even if the process is already gone (kills zombies). Does nothing if the process does not exist. Return process exit status. r)wait_pidcht|tjrts|n||t r]t|tjrE t j|j|S#t j $rYdSwxYwdSdSr) rrrrrr rrr NoSuchProcess)procrs rrzterminate..waits dJ, - - c  IIKKKK IIg     z$ (899  ~dh//44W==='         s.+BB-,B-ctrtr tj}tr/|tjkr|tj||dSr)r rdsignalSIGKILLr send_signalSIGCONT)r!sigs rsendsigzterminate..sendsigs^  !^ !.C  -SFN**   V^ , , , rc |n@#t$r3}tr |jdkrn|jtjkrYd}~nd}~wwxYw||S)N)OSErrorr winerrorerrnoESRCH)r!rerrr(r'rs r term_subproczterminate..term_subprocs~  GD#        3<1,,ek))   tD'"""s  A )AA cb |n#tj$rYnwxYw||Sr)rr )r!rr(r'rs r term_psproczterminate..term_psprocsR  GD#    #    D tD'"""s ""c tj|}||S#tj$rtr||cYSYdSwxYwr)rrr r )rrr!r2rs rterm_pidzterminate..term_pidsz .>#&&D ;tW-- - # . . . .xW----- . . . .s#"A  A c|jr|j|jr|j|jr|jdSdSr)r}rr~r)r!s r flush_popenzterminate..flush_popensl ; K      ; K      :  J         rz wrong type %r) r psutil._psposixrrrrrrr pid_existsr TypeError) proc_or_pidr' wait_timeoutr0r4r6rrr(r2rrs ` @@@@rr<r<s -,,,,,,   ##############...... A / a   18A|,, a**FL9 : :  KNNNa%%0aa15$S))..3..).FNFL9 : : 1;q,// a**FL9 : :  KNNNa%%0aa15$S))..3..).:+ , , 1<<00 a**FL9 : :  KNNNa%%0aa15$S))..3..). Oa/00 0 a**FL9 : :  KNNNa%%0aa15$S))..3..)))))s H1H %H3HA/I4ctj|}tr/t}t |t/t r/t }t |t /|rf|D]}t |dtj|t\}}|D]1}td|zt |tj 0dSdS)aTerminate and wait() any subprocess started by this test suite and any children currently running, ensuring that no processes stick around to hog resources. If resursive is True it also tries to terminate and wait() all grandchildren started by this process.  recursiveN)r;rz0couldn't terminate process %r; attempting kill())r') rrchildrenrpopr<r wait_procsr r`r#r$)r>r?rrrgonealives rr=r=3s~((9(==H $((**$  !!#  - , ,A ad + + + + +'.III e - -A CaG H H H aV^ , , , , , -- - -rctstdd}tjd}|D]"}|s|dkr||z }"|st d|zd}d}|d}t|d}t|dkrt|d}t|dkrt|d}|||fS) z"Return a tuple such as (2, 6, 36).z not POSIXr.zcan't parse %rrr) r NotImplementedErrorrunameisdigitrsplitrlen)rrIcminormicronumsmajors rrSrSXs /!+... A HJJqME  99;; !s(( FAA  3)E1222 E E 773<.wrappersC  3//////~C{. C(((JJLLLHHHH    s A2AA)rr decorator)rrrs`` r__call__zretry.__call__sF           $!r) rrrrrrrerrkrrr]r]sl%       &&&rr]r)r_rbrrachtj|trtjddSdS)zWait for pid to show up in the process list then return. Used in the test suite to give time the sub process to initialize. {Gz?N)rrr rr)rs rrUrUs<  N3 4rTct|d5}|}dddn #1swxYwY|s|sJ|rt||S)z8Wait for a file to be written on disk with some content.rbN)r readrM)fnamerrr datas rrVrVs eT  avvxx  t E Ks 266c<|}t|sJ|S)zVKeep calling function for timeout secs and exit if eval() expression is True. )eval)rexprrets rrTrTs% #%%C ::: JrcDd} tj|}tj|jr t jt j|}nt jtj|}tr |dS||dS#t$rYdSwxYw)z>Convenience function for removing temporary test files or dirsc\tjtz}tj|kry |S#t$rYn7t$r+}|}t dt |zYd}~nd}~wwxYwtjdtj|ky|)Nz ignoring %srn)rr r WindowsErrorr`rr)rrdrr/s r retry_funzsafe_rmpath..retry_funs )++.ikkG## 1suu $    1 1 1]c#hh/00000000 1 Jt   ikkG## s > A> A>!A99A>N) rstatS_ISDIRst_moderpartialshutilrmtreeremover r)rr{strs rrMrMs"  WT]] < # # 5#FM488CC#BIt44C   CEEEEE IcNNNNN      sA=B B BBcR tj|dS#t$rYdSwxYw)z-Convenience function for creating a directoryN)rmkdirrrs r safe_mkdirrs:        s  &&c#Ktj} tj|dVtj|dS#tj|wxYw)z@Context manager which temporarily changes the current directory.N)rrrL)dirnamecurdirs rrLrLs]Y[[F   s AActj|r J||rtdst dt |t rtjd}t |ts J|ttdd5}| |dddn #1swxYwY tjd|jd|gt!|jdS#t!|jwxYwt#jt&|t(r=tj|}tj||jt*jzdSdS) z1Creates an executable file in the given location.gcczgcc is not installedz #include int main() { pause(); return 1; } z.csuffixrNz-o)rrrrrrboolrrrr rQr rrrrMrcopyfiler$r r|chmodr~S_IEXEC)outpathc_coder rs rrNrNsw~~g&&//// & 9U|| 5344 4 fd # # _F&#&&....& *D)))4 0 0 A GGFOOO                 !5!&$"@ A A A      K      G,,,  9!!B HWbj4<7 8 8 8 8 8 9 9s0CCCDD'rEc tjt||}tj|stj|S[)zReturn an absolute pathname of a file or dir that did not exist at the time this call is made. Also schedule it for safe deletion at interpreter exit. It's technically racy but probably not really due to the time variant. T)prefixrr)tempfilemktempr'rrrr)rrrs rrQrQ9sN *mFLLLw~~d## *7##D)) )*rc\eZdZdZeejds ejjZe sdZ dSdS)TestCasec|jj}|dsd|z}|d|jjd|jS)Nzpsutil.z psutil.tests.rF)rrrr_testMethodName)rfqmods r__str__zTestCase.__str__NsT) ** ,#e+E EE4>***D,@,@B BrassertRaisesRegexcdSrrlrs rrunTestzTestCase.runTest\s DrN) rrrrrUunittestrassertRaisesRegexprrrrlrrrrJspBBB 78$&9 : :A$-@      rrc8eZdZdZd dZdZdZdZdZd Z dS) rFzUTest class providing auto-cleanup wrappers on top of process test utilities. rENc^t||}|t||S)N)rr)rQ addCleanuprM)rrrrrs rrQzPsutilTestCase.get_testfnis-&c222  U+++ rcTt|i|}|t||Sr)r>rr<)rrrrs rr>zPsutilTestCase.spawn_testprocns----  5))) rct\}}|t||t|||fSr)r@rr<)rchild1child2s rr@z"PsutilTestCase.spawn_children_pairssD,..  6***  6***rct\}}|t||t|||fSr)r?rr<)rrrs rr?zPsutilTestCase.spawn_zombieysB%  6***  6***rct|i|\}}|t||t||Sr)r;rrMr<)rrrrr s rr;zPsutilTestCase.pyrunsE---w  W---  5))) rc*|tjtj|jt |tjtjfrh|rJ |}td|z#tj$rYnwxYw| dtj |jrJ|j| |jtj dS)Nz3Process.status() didn't raise exception (status=%s)rr) assertRaisesrr rrrr is_runningrAssertionErrorrr8 assertNotInpids)rr!rs rassertProcessGonez PsutilTestCase.assertProcessGones &.III dV^V\: ; ; !(( ( (( =%&35;&<==='     IIaI $TX..8888. 6;==11111s.BB&%B&rEN) rrrrrQr>r@r?r;rrlrrrFrFds}         2 2 2 2 2rrFzunreliable on PYPYceZdZdZdZdZdZerdndZdZ e j Z dZ dZd Zd Zd Zd Zd Z ddZdZdS)rEaTest framework class for detecting function memory leaks, typically functions implemented in C which forgot to free() memory from the heap. It does so by checking whether the process memory usage increased before and after calling the function many times. Note that this is hard (probably impossible) to do reliably, due to how the OS handles memory, the GC and so on (memory can even decrease!). In order to avoid false positives, in case of failure (mem > 0) we retry the test for up to 5 times, increasing call repetitions each time. If the memory keeps increasing then it's a failure. If available (Linux, OSX, Windows), USS memory is used for comparison, since it's supposed to be more precise, see: https://gmpy.dev/blog/2016/real-process-memory-and-environ-in-python If not, RSS memory is used. mallinfo() on Linux and _heapwalk() on Windows may give even more precision, but at the moment are not implemented. PyPy appears to be completely unstable for this framework, probably because of its JIT, so tests on PYPY are skipped. Usage: class TestLeaks(psutil.tests.TestMemoryLeak): def test_fun(self): self.execute(some_function) rfrrgTc`|j}t|d|jS)Nuss) _thisprocmemory_full_inforrss)rmems r_get_memzTestMemoryLeak._get_mems+n--//sE37+++rcttr|jS|jSr)r rnum_fds num_handlesrs r _get_num_fdszTestMemoryLeak._get_num_fdss2  0>))++ +>--// /rcP|jrt|dtjdSdS)Nyellow)colorfile)verboserrr~)rmsgs r_logzTestMemoryLeak._logs3 < > 8#* = = = = = = > >rc<|}|||}||z }|dkr|d|z|dkr5trdnd}|dkr|dz }|d|d|}||d S) zMakes sure num_fds() (POSIX) or num_handles() (Windows) does not increase after calling a function. Used to discover forgotten close(2) and CloseHandle syscalls. rzHnegative diff %r (gc probably collected a resource from a previous test)fdhandlerGrz unclosed z after calling N)rcallfailr )rrbeforeafterdifftype_rs r _check_fdszTestMemoryLeak._check_fdss ""$$ #!!##v~ !88))=?CDEE E !88!/DDxEaxx 7;ttUUUCCHC))C.. 8rcFtjd|}t|D]}||}~~tjd|}|tjg||z }|S)zGet 2 distinct memory samples, before and after having called fun repeadetly, and return the memory difference. rG) generation)gccollectrrr assertEqualgarbage)rrtimesmem1rrwmem2rs r _call_ntimeszTestMemoryLeak._call_ntimess a    }}u  A))C..C33 a    }} R(((d{ rc g}d}|}td|dzD]} |||} d| dt| dt| |z d|} || | |kp| |k} | r| dkr|| dS| dkrt || ||z }| }|d|)NrrGzRun #z : extra-mem=z , per-call=z, calls=z. )rrrappendrprintrr) rrr warmup_timesr` tolerancemessagesprev_memincreaseidxrrsuccesss r _check_memzTestMemoryLeak._check_memsGaK((  C##C//CC[%%%%{3;'?'?'?'?HC OOC Y&9#/G 77IIcNNN!88GGG #!ii (++,,,rc|Srrl)rrs rrzTestMemoryLeak.calls suu rNc||n|j}||n|j}||n|j}||n|j} |dks Jd|dks Jd|dks Jd|dks Jdn.#t$r!}t t |d}~wwxYw|||||| |||||dS) zTest a callable.NrGztimes must be >= 1rzwarmup_times must be >= 0zretries must be >= 0ztolerance must be >= 0)rrr`r) rrr`rrrrrrr)rrrrr`rr/s rexecutezTestMemoryLeak.execute s3* '3'?||" $0''dl!*!6IIDN  'A:::3:::1$$$&A$$$a<<>>#;>>>> ' ' 'SXX&& & ' #|,,,  5| '9  > > > > >sAA// B9BBc 6fd}j|fi|dS)znConvenience method to test a callable while making sure it raises an exception on every call. c4dSr)r)rirrsrrz*TestMemoryLeak.execute_w_exc..call"s   c3 ' ' ' ' 'rN)r)rrirrrs``` r execute_w_exczTestMemoryLeak.execute_w_excsJ ( ( ( ( ( ( (  T$$V$$$$$r)NNNN)rrrrrrrr*r`rrrrrrrrrrrrrrlrrrErEs< ELI%bbAGG  I,,, 000 >>>!!!&   ---0CG>>>>*%%%%%rrEc ddl}ddl}ddl}ddl}ddl}ddl} ddl}n#t$rd}YnwxYw ddl}n#t$rd}YnwxYw| }tj r"tdrtd|d<ntjr!d|dz|d<ntjrvddt%t&|z|d<t+|dr%|dxxd |zz cc<n.|d||d<d t3||gz|d <tjr|d |d <d ||| g|d <tC|dd|d<||dxxd|j"zz cc<tjrrtdr=tddg} t'| #dd|d<nd|d<|$d} | r| |d<tKj&|d<|'} | dd | d|d<|j(tj)*d|d<|j+*d|d<|,|d<tZj./d|d<t[j0|d<tb|d <|2|d!<t[j3|d"<tj4|d#<d$tkd%tj6Dz|d&<tj7} tq| j9d'tu| j;d(tu| j<|d)<tj=} tq| j9d'tu| j;d(tu| j<|d*<t}tj?|d+<tj@A}|Bd,d|C||d-<td.tJjE/|FD])\}}t|d0zd1d|tJjE/*td.tJjE/tJjGHdS)2Nr lsb_releasezlsb_release -d -sOSz Darwin %szWindows  win32_editionz, archrkernelr __version__z not installedpipz (wheel=%s)rz --versionrrGglibcz fs-encodinglangz%Y-%m-%d %H:%M:%Sz boot-timeruser~homerpyexehostnamePIDcpusz%.1f%%, %.1f%%, %.1f%%c@g|]}|tjz dzS)d)r cpu_countrs rrz!print_sysinfo..ps+IIIq6#%%%+IIIrloadavgz%, used=z, total=memoryswaprrrr!zF======================================================================r:17)I collectionsdatetimegetpasslocaleplatformpprintr ImportErrorwheel OrderedDictrr rrOSXmac_verr rmapr win32_verrUrsystemversionlist architecturemachiner rIpython_implementationpython_versionpython_compilerrrrKlibc_verrgetfilesystemencoding getlocale fromtimestamp boot_timestrftimenowgetuserrr expanduserrr$nodegetpidrtuplerovirtual_memoryrpercentrusedtotal swap_memoryrLrras_dictr@pformatrr~itemsr}flush)rr r r r r rrinfooutrrrrpinfokvs rrIrI(sOOONNNMMMOOOMMM    " " $ $D| Gm,, G+,,T G 8#3#3#5#5a#88T G#(( X'')) * *#,#,,T 8_ - - : JJJ$!7!7!9!99 9JJJ ( 1 1 1 183C3C3E3E3EFT 99 X " " $ $%%)9)9););(<<>>DL |-!))!,XYY&&((!!  "" $%%DN#}o>>DK  U }u'888 | << *e[)**Cc((....q1DKK)DK      "  DM355D     D#AwwwQ0DL )77$H%899 $((**334GHHDL??$$DL7%%c**DL)++DKDM}}D)++DK#%%DL. IIV5F5H5HIIIJJLDO   ! !C CK+ch////SY1G1G1GIDN    D DL;ty1111;tz3J3J3JLDLv{}}%%DL N   $ $ & &E IImT""">>%((DL ($$$$ ::1 AGGGGQQ'cj99999 ($$$$Js ..7 AActj}t|dr|St|dr&t j|SdS)Nrtrmr)rrrUrtrandomchoicerm)rs r_get_eligible_cpur:s`Aq)/yy{{ N # #/}Q^^--... 1rceZdZdZddifddifgZddifddddifd difd difd difd difd difddifddifg Zddifddddifddifddifddifddifddifddifddifddifddifddifddifd difd!difd"difd#difgZer$ed$difgz Zed%difgz Zed&difgz Zed'difgz Zer ed(difgz Ze r ed)difgz Ze red*e j fifgz Ze r ed+difgz Zer ed,difgz Zer ed-difgz Zer ed.difgz Zer ed/dd0d1ifgz ZgZer eddifgz Znede jfifgz Ze red*e j d2fifgz Ze r"ered)e jd3fifgz Zned)e jfifgz Ze red+egfifgz Zd4ejfifd5difd6difd7difd8difgZered4ejfifgz Zed4ejfifgz ZeezezezZd9Zd?d:Zd;Z e!d<Z"e!d=Z#d>S)@rGaA container that lists all Process class method names + some reasonable parameters to be called with. Utility methods (parent(), children(), ...) are excluded. >>> ns = process_namespace(psutil.Process()) >>> for fun, name in ns.iter(ns.getters): ... fun() cpu_percentrlmemory_percentr.r?r>Trmemory_info_exoneshotrparentsrrrcmdline connectionskindall cpu_times create_timerrr memory_infornicenum_ctx_switches num_threads open_filesppidrrzusernameuidsgidsterminalrrurqrvrmrtrprrrgroupedF)rirr%suspendresumer<killc||_dSr)_proc)rr!s rrzprocess_namespace.__init__s  rc#Kt|}tj||D]L\}}}|r|t |j|}t j|g|Ri|}||fVMdSz_Given a list of tuples yields a set of (fun, fun_name) tuples in random order. N)rr8shuffle clear_cacherrWrr)rlsr[fun_namerrrs riterzprocess_namespace.iters"XXr$& " " HdD #  """$*h//C#C7$777$77C/ ! ! ! !  " "rcR|j|jjddS)z&Clear the cache of a Process instance.T) _ignore_nspN)rW_initrrs rr[zprocess_namespace.clear_caches' T:::::rc|D]<\}}}d|z}t||s!|jjd|d}t|=dS)z}Given a TestCase instance and a list of tuples checks that the class defines the required test method names. test_z class should define a 'z' methodN)rUrrAttributeError)cls test_classr\r]r meth_namers rtest_class_coveragez%process_namespace.test_class_coveragesn ! * *NHa(*I:y11 *(111999>$S))) * * *rctd|jD}td|jD}tdttjD}||z|z }|rt d|zdS)Ncg|] }|d SrArlrs rrz*process_namespace.test.. s***QAaD***rcg|] }|d SrArlrs rrz*process_namespace.test..s111qt111rc*g|]}|ddk|S)rrrlrs rrz*process_namespace.test..s!CCC1qts{{Q{{{rz!uncovered Process class names: %r)rrEignoredrrrr)rethisrmklassleftouts rtestzprocess_namespace.test s**#'***++11S[11122CCFN 3 3CCCDD'>U*  L@7JKK K L LrN)T)$rrrrutilsrmgettersr r1r2r5r RLIMIT_NOFILEr.r4r0r r3settersNORMAL_PRIORITY_CLASSr IOPRIO_CLASS_NONE IOPRIO_NORMALr:r#SIGTERMkillers CTRL_C_EVENTCTRL_BREAK_EVENTrErr^r[ classmethodrhrqrlrrrGrGsu B 2r" E B R+t,- r2 2r" B 2r B B  G B VUO, b" B B B R$ B R R R$ B r2 R 2r B R#G& )VR$%%VR$%%ZR())YB'((-]B+,,(Xr2&''>X 47<==.^R,--)YB'(()YB'((-]B+,,=]BE(:;<<G DVUB'((Vf:=rBCCJX 4lCRHIIB  B F$CDD *B/ B 2r b" R GF]V%8$;R@AA]V%<$?DEE '/G #g -C " " " ";;; * *[ *LL[LLLrrGceZdZdZddifddddifddddifddifd dd difd dd difd dd difd dddifdejfifddddifddifddifddddifdejfifddifddifddifddifgZer eddd difgz Ze r eddifgz Ze r eddifgz Ze r eddifgz Ze r eddifgz Ze red difgz Zed!d"ifgz Zd#difd$ejgfifd%difd&difgZeZed'ZejZd(S))rHzA container that lists all the module-level, system-related APIs. Utilities such as cpu_percent() are excluded. Usage: >>> ns = system_namespace >>> for fun, name in ns.iter(ns.getters): ... fun() r!rlrlogicalFT cpu_statsrFpercpudisk_io_countersperdiskdisk_partitionsrE disk_usagenet_connectionsrD net_if_addrs net_if_statsrspernicr8rr-usersr)rnroryrxrwwin_service_iterwin_service_get)alg process_iterrAr<cpu_times_percentc#Kt|}tj||D]6\}}}tt|}t j|g|Ri|}||fV7dSrY)rr8rZrrrr)r\r]rrrs rr^zsystem_namespace.iterHs "XXr$& " " HdD&(++C#C7$777$77C/ ! ! ! ! " "rN)rrrrrrr'rsr/HAS_GETLOADAVGr9r8r6r rrrmrE staticmethodr^rGrhrlrrrHrHsD b" b9e,- b9d+, b" b8U+, b8T*+ R)T!23 B .   + B0 R R B4 01   + R B "b 2r"%G(8Zh%5677,\2r*++6+R455.^R,--1&B/008'R011& 2677 R ))*-r2 B b"% G C " "\ ",?rrHcPtj|s J|d|_|S)zA decorator to mark a TestCase class. When running parallel tests, class' unit tests will be run serially (1 process). T)inspectisclass _serialrun)ros r serialrunrWs/ ?5 ! !((5(( !E Lrc8d}ttd||S)zZDecorator which runs a test function and retries N times before actually failing. cBtd|ztjdS)Nz %r, retryingr)rrr~)ris rrbz retry_on_failure..logfunes" ns"444444rN)r_rr`rb)r]r)r`rbs rrDrDas3555 >4    rcfd}|S)z,Decorator to Ignore AccessDenied exceptions.cJtjfd}|S)Ncn |i|S#tj$rstjdwxYw)Nzraises AccessDenied)r AccessDeniedrSkipTest)rrronly_ifs rrz9skip_on_access_denied..decorator..wrapperos^ ?sD+F+++& ? ? ?&"'(=>>>  ?s )4rrrrs` rrjz(skip_on_access_denied..decoratorns>    ? ? ? ? ?   ?rrlrrjs` rrBrBls$      rcfd}|S)z3Decorator to Ignore NotImplementedError exceptions.cJtjfd}|S)Ncx |i|S#t$r$sdjz}tj|wxYw)Nz4%r was skipped because it raised NotImplementedError)rHrrr)rrrrrs rrz;skip_on_not_implemented..decorator..wrappersi -sD+F+++& - - -&"L %',,,  -s .9rrs` rrjz*skip_on_not_implemented..decorator~s>    - - - - -   -rrlrs` rrCrC|s$      r 127.0.0.1ctjtj5}||df|dcdddS#1swxYwYdS)z6Return an unused TCP port. Subject to race conditions.rrGN) contextlibclosingsocketbind getsockname)hostrs rrXrXs  FMOO , ,% 4)!!!$%%%%%%%%%%%%%%%%%%s1A$$A(+A(c||ttfvrd}tj||} tjdvr+|tjtjd|||tj kr| d|S#t$r| wxYw)zBinds a generic socket.NrEr)ntcygwinrGrg) rrrrr setsockopt SOL_SOCKET SO_REUSEADDRrrlistenrr)familytypeaddrrs rrYrYs |7H"555 = & &D  7* * * OOF-v/BA F F F $ 6% % % KKNNN   s A4B CcptjsJtj|r J|t jt j|} |||t jkr| dn##t$r| wxYw|S)zBind a UNIX socket.rg) rr rrrrrrrrrr)rrrs rrZrZs <<w~~d##))T)) # = . .D $ 6% % % KKNNN    Ks :B B3rcFtjtj|t5}|||d|}tj|t} |||} |\}}||kr||fcdddS| B#t$r| wxYw#1swxYwYdS)z^Build a pair of TCP sockets connected to each other. Return a (server, client) tuple. rgTN) rrrrrrrconnectrrr+)rrllrMcaddras rr[r[sH  FM&+>> ? ?2   ! ~~ M&+ . .  IIdOOOMMOOE ))++45==q6       GGIII  s+ADA C3C33 DDDDctjsJdx}} t|tj}|dtjtjtj}|d||n;#t$r.|| || wxYw||fS)zBuild a pair of UNIX sockets connected to each other through the same UNIX file name. Return a (server, client) tuple. Nrr) rr rZrr setblockingrrrr)rserverclients rr\r\s <<FV !$V-?@@@1v~v/ABB1t    LLNNN   LLNNN  F s BB8Cc#Kg}dx}} |ttjtj|ttjtjt rn|ttjtj|ttjtjtrmtrft}t}t|\}}t|tj}|||fD]}|||V|D]}| ||fD]}|t|dS#|D]}| ||fD]}|t|wxYw)z1Open as many socket families / types as possible.Nr)rrYrrr SOCK_DGRAMrrr HAS_CONNECTIONS_UNIXrQr\rZrrM)socksfname1fname2s1s2s3rrrs rr]r]s EFV# [1CDDEEE [1BCCDDD ?? J LLV_f6HII J J J LLV_f6GHH I I I  ) \\F\\F$V,,FB!&v/@AAAB"b\   Q   A GGIIIIf% # #E E""" # #  A GGIIIIf% # #E E""" #s E"F3Gcddl}tr2tr+ts$t |tjs J||t jkrd|dD}t|dks J||D]}d|cxkrdks nJ|tst|}| |dS|t j krLt |ts J|tst|}||dS|tjkr!t#jd| J|dSt'd|) z[Check a net address validity. Supported families are IPv4, IPv6 and MAC addresses. rNc,g|]}t|Srl)rrs rrz%check_net_address.. s0001A000rrFrz([a-fA-F0-9]{2}[:|\-]?){6}zunknown family %r) ipaddressenumrr#rIntEnumrrrKrLr IPv4Addressrr IPv6AddressrAF_LINKrVmatchr)rrroctsnums rrWrWs 88D8&$,//7777/ 00 30004yyA~~~t~~~ ) )C????s?????D???? !4==Dd##### 6? " "$$$**d**$ !4==Dd##### 6> ! !x5t<<HH$HHHHH,f555rcd}d}d}d}d}||||||||||dS)z*Check validity of a connection namedtuple.cDt|dk}t|dvsJt||d|jksJ|j|d|jksJ|j|d|jksJ|j|d|jksJ|j|d|jksJ|j|d|jksJ|j|r |d |jksJ|jdSdS) N)r*rrrGrrrrgr*)rLrrrladdrraddrrr)rhas_pids r check_ntuplez-check_connection_ntuple..check_ntuple s5d))q.4yyF"""CII"""Aw$'!!!47!!!Aw$+%%%t{%%%Aw$)###TY###Aw$*$$$dj$$$Aw$*$$$dj$$$Aw$+%%%t{%%%  17dh&&&&&& 1 1&&rc|jtttfvsJ|jt*t |jtjs J|n$t |jts J||jtkrtj|j|j }tj |5 | |j ddfn2#tj$r }|jtjkrYd}~nd}~wwxYwddddS#1swxYwYdS|jtkr$|jt$jksJ|jdSdS)Nr)rrrrrrrrrrrrrrerrorr- EADDRNOTAVAILrr CONN_NONE)rrr/s r check_familyz-check_connection_ntuple..check_family,s{w'::::DK:::  dk4<88 > >$ > >8 >dk3// 5 5 5 5/ ;' ! !  dk4955A#A&&  FFDJqM1-....|yE$77787777                   [G # #;&"2222DK222$ #22s<D'"C('D'(D7D D'DD''D+.D+cttdt}|jtjtj|fvsJ|jt *t|jt js J|n$t|jts J||jtjkr$|j tj ksJ|j dSdS)NSOCK_SEQPACKET) rrobjectrrrrrrrrrr)rrs r check_typez+check_connection_ntuple..check_typeAs )9688DDyV/1B+----.2i---  di66 < < < <6 <di-- 3 3t 3 3- 9) ) );&"2222DK222 * )22rc|j|jfD]}|jttfvrt |t sJt||sFt |jtsJt|jd|jcxkrdksnJ|jt|j |j|jtkr,t |tsJt|dS)Nri)rrrrrrr(rportrrWiprr)rrs r check_addrsz,check_connection_ntuple..check_addrsMsZ, 9 9D{w111!$..::T ::.!$)S11BB4 ??BB1DI......... ...!$'4;7777''!$,,88d4jj88, 9 9rct|jtsJ|jdttD}|j|vsJ|j|jt tfvr6|jtkr&|jtj ksJ|jdS|jtj ksJ|jdS)Ncbg|],}|dtt|-S)CONN_rrs rrzAcheck_connection_ntuple..check_status..\sB,,,\\'**,'&!$$,,,r) rrrrrrrrrrr)rvalidss r check_statusz-check_connection_ntuple..check_statusZs$+s++88T[88+,,c&kk,,,{f$$$dk$$$ ;7H- - -$){2J2J;&"2222DK22222;&"2222DK22222rNrl)rrrrrrs rcheck_connection_ntuplers 1 1 1@@@* @ @ @ 9 9 9@@@LLJtKLrc ddl}t|dst ||S#t$rddl}||cYSwxYw)z,Backport of importlib.reload of Python 3.3+.rNreload) importlibrUrrimp)modulerrs rr^r^ps(y(++    ''' """ zz&!!!!!"s3#AActjtj|d}tjddkrddl}|||Stjdddkr$ddlm }||| Sddl }|j ||}|j |}|j||S)Nrrr)SourceFileLoader)rrsplitextrrrr load_sourceimportlib.machineryr load_moduleimportlib.utilutilspec_from_file_locationmodule_from_specloader exec_module)rrrrrspecmods rr_r_}s 7  BG,,T22 3 3A 6D a tT*** "1"  ' '888888d++77999~55dDAAn--d33 $$$ rc:tj|tdS)zRaise a warning msg.N)warningsr` UserWarning)rs rr`r`s M#{#####rct|}|j}t|dks|dtkrdSt |dd}t |tsdSt d|DS)z-Check if object is an instance of namedtuple.rGrF_fieldsNc3FK|]}t|tkVdSr)rr)rns r z is_namedtuple..s,))!tAww#~))))))r)r __bases__rLr(rrrE)rtbr s rrbrbsy QA A 1vv{{ademmu9d##A a  u ))q))) ) ))rc#|Ktrdnddt|z}fdtjD}t j|}tj|| tj ||Vt|dS#t|wxYw)zCtx manager which picks up a random shared CO lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized path. rrz.sorcg|]R}tj|jdkr"|jvK|jSS)rG)rrrlower)rrrexts rrz'copyload_shared_lib..s['''1  ((+s22qv||~~%%%%%rN) r#rQrrrrr8r9rrctypesCDLLrM)rdstlibsrrrs @@rraras *ff( ---''''' 0 0 < < > >'''mD!!S!!!  K   III      K    s B**B;c# Kddlm}ddlm}d t| z} fdt jD}tr1|s/dt jD}tj |}tj ||d} tj |}|V|Ctj jj}|jg|_||j}|dkr |t'|dS#|Ctj jj}|jg|_||j}|dkr |t'|wxYw) zCtx manager which picks up a random shared DLL lib used by this process, copies it in another location and loads it in memory via ctypes. Return the new absolutized, normcased path. r)wintypes)WinErrorz.dllrcg|]}|jrZdtj|jvr"d|jv|jS)rwow64)rrrrr)rrrs rrz'copyload_shared_lib..s///1 '',,/BG,,QV44::<<<<qv||~~--.--rcg|]A}dtj|jv:|jBS)r)rrrrrs rrz'copyload_shared_lib..sO@@@qbg..qv66<<>>>>F>>>rN)rrrrQrrrrr#r8r9rrWinDLLwindllkernel32 FreeLibraryHMODULEargtypes_handlerM) rrrrrrcfiler!rwrs @rraras $########### ---//// 0 0 < < > >///  @ @@@FN$4$4$@$@$B$B@@@DmD!!S!!! M#&&EIII $m4@ (0(8'9 $!k%-00!88HJJJ        $m4@ (0(8'9 $!k%-00!88HJJJ     s :D((AE>c&tddS)NTr=)r=rlrrcleanup_test_procsr'sD!!!!!!rc*tj|Sr)rexit)r'frames rrrsSXc]]rr)F)TFr)r)r)rE)r __future__ratexitrrr-rrrrr8rVrrr#rr|rrrrrrrrrrrrrr r r r r psutil._commonrrrpsutil._compatrrrrrrrrr unittest2rrcatch_warnings simplefilterrr__all__builtin_module_namesr#rprrdr*maxsizer-r"r!r,r rr'r'r(decoder)rrASCII_FSrrrr__file__r%r&HERErrUrr.r/rr0r2r3HAS_NET_IO_COUNTERSr4r1r5r6rrwr7rr8r9 HAS_THREADSgetuid SKIP_SYSCONSrr$r devnullrregisterrrr+rrrrrrrrrr>r@r?r;rryr<r=rSrRr]r rUrrVrTrMrcontextmanagerrLrNrQrrFskipIfrErIr:rGrHrrDrBrCrXrYrZr[r\r]rWrr^r_r`rbrar'rlrrrAs &%%%%%       &&&&&&&&&&&&((((((******,,,,,, """""" !OOOO      " "h'''  vKKKK D$ $ $ ZS--  #!RZ/O>RZ3O  ' ;   #' !OJaNA 7f!IBIKK/MM!IBIKK/M9))009JKK( $3 $ & & , , . .2G G 7  GLL**D$77 9 9gll8Y//  w1122*U76>>::wvz** ..gfni00 WV^X . . '&.-88gf&78876>955wv~}== WV^X . . gf&788%H$$/Ev/E/G/G*H*HKKKKK76>22"76+ABBgfni00  2)")++"2 @[]] $rz4  3333v;;333 '&)VVXX . . (((((!(((`$$$$N###L***Z&6 &~NU/U/U/U/p----J!!!0   (77777F777t%dN#^4T/////n   B    9999< * * * *"x ..2.2.2.2.2X.2.2.2b+,,O%O%O%O%O%^O%O%-,O%dXXXv   FLFLFLFLFLFLFLFLR?@?@?@?@?@?@?@?@D(         0%%%%[t"!' 2    .. ###46664JJJd ( ( (   *$$$ * * * 9&####X""" DFM&."B"BCCCCCDDsH/C66D9 D+ D9+D/ /D92D/ 3D98D9"M==NN