U-4dZddlmZmZmZmZddlZddlmZgdZ GddZ Gd d Z Gd d e Z dS) zlModule containing a memory memory manager which provides a sliding window on a number of memory mapped files) MapWindow MapRegion MapRegionList is_64_bitN)reduce)StaticWindowMapManagerSlidingWindowMapManager WindowCursorceZdZdZdZddZdZdZdZdZ d Z d Z d Z dd Z dZdZdZdZdZdZdZdZdZdZdZdZdZdZdS)r a Pointer into the mapped region of the memory manager, keeping the map alive until it is destroyed and no other client uses it. Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager **Note:**: The current implementation is suited for static and sliding window managers, but it also means that it must be suited for the somewhat quite different sliding manager. It could be improved, but I see no real need to do so._manager_rlist_region_ofs_sizeNcL||_||_d|_d|_d|_dS)Nrr )selfmanagerregionss /srv/buildsys-work-dir/castor/build_node/builder-2/WGSG1/unpkd_srcs/cloudlinux-venv-1.0.6/venv/lib/python3.11/site-packages/smmap/mman.py__init__zWindowCursor.__init__%s)     c.|dSN_destroyrs r__del__zWindowCursor.__del__, rc|Srrs r __enter__zWindowCursor.__enter__/s rc.|dSrr)rexc_type exc_value tracebacks r__exit__zWindowCursor.__exit__2r rc||jk t|jdkr8|jj|jdSdS#ttf$rYdSwxYwdS)z&Destruction code to decrement countersNr) unuse_regionrlenr_fdictpop path_or_fd TypeErrorKeyErrorrs rrzWindowCursor._destroy5s  ; " t{##q((M(,,T[-C-C-E-EFFFFF)(x(       # "sAA//BBc4|j|_t|j|j|_|j|_|j|_|j|_|jD]}||j|jdSdS)z>Copy all data from rhs into this instance, handles usage countN)rtyperrrrincrement_client_count)rrhsregions r _copy_fromzWindowCursor._copy_fromJs  &d3:&&sz22 { H Y k , ,F  ) ) + + + + < # L / / 1 1 1 1 1 $ #rc^t|}|||S)zcopy module interface)r2r6)rcpys r__copy__zWindowCursor.__copy__Ys*d4jjll t rcX|||dS)zAssign rhs to this instance. This is required in order to get a real copy. Alternativly, you can copy an existing instance using the copy moduleN)rr6)rr4s rassignzWindowCursor.assign`s)  rrcd}|j}|j}t|p||p|}|j1|j|rd}n|||kr|S|r<||j|||d|_|j ||jj z |_ t||j |z |_ |S)a$Assure we point to a window which allows access to the given offset into the file :param offset: absolute offset in bytes into the file :param size: amount of bytes to map. If 0, all available bytes will be mapped :param flags: additional flags to be given to os.open in case a file handle is initially opened for mapping. Has no effect if a region can actually be reused. :return: this instance - it should be queried for whether it points to a valid memory region. This is not the case if the mapping failed because we reached the end of the file **Note:**: The size actually mapped may be smaller than the given size. If that is the case, either the file has reached its end, or the map was created between two existing regionsTNF)rr file_sizemin window_sizer includes_ofsr*_obtain_regionr3_brofs_endr)roffsetsizeflags need_regionmanfsizes r use_regionzWindowCursor.use_regionfs m %%''4=5#//"3"3"??  rcV|j|jdd|_dS)a/Unuse the current region. Does nothing if we have no current region **Note:** the cursor unuses the region automatically upon destruction. It is recommended to un-use the region once you are done reading from it in persistent cursors as it helps to free up resource more quicklyN)rr3rs rr*zWindowCursor.unuse_regions- < # L / / 3 3 3 rct|j|j|j|jzS)aReturn a buffer object which allows access to our memory region from our offset to the window size. Please note that it might be smaller than you requested when calling use_region() **Note:** You can only obtain a buffer if this instance is_valid() ! **Note:** buffers should not be cached passed the duration of your access as it will prevent resources from being freed even though they might not be accounted for anymore !) memoryviewrbufferrrrs rrOzWindowCursor.buffers5$,--//0049TZ;O1OPPrc4|jS)a :return: the underlying raw memory map. Please not that the offset and size is likely to be different to what you set as offset and size. Use it only if you are sure about the region it maps, which is the whole file in case of StaticWindowMapManager)rmaprs rrQzWindowCursor.maps |!!!rc|jduS)z2:return: True if we have a valid and usable regionNrrs ris_validzWindowCursor.is_valids|4''rc|jduS)z?:return: True if we are associated with a specific file alreadyN)rrs r is_associatedzWindowCursor.is_associateds{$&&rc*|jj|jzS)zh:return: offset to the first byte pointed to by our cursor **Note:** only if is_valid() is True)rrBrrs r ofs_beginzWindowCursor.ofs_begins|**rc:|jj|jz|jzS)z3:return: offset to one past the last available byterrBrrrs rrCzWindowCursor.ofs_ends|*TZ77rc|jS)z$:return: amount of bytes we point to)rrs rrEzWindowCursor.sizes zrc|jS)z:return: our mapped region, or None if nothing is mapped yet :raise AssertionError: if we have no current region. This is only useful for debuggingrSrs rr5zWindowCursor.regions |rcz|jj|jz|cxko|jj|jz|jzkncS)z:return: True if the given absolute offset is contained in the cursors current region **Note:** cursor must be valid for this to workrZ)rofss rr@zWindowCursor.includes_ofssE  $)+````t|7RUYU_7_`````rc4|jS)z$:return: size of the underlying file)rr=rs rr=zWindowCursor.file_sizes{$$&&&rc4|jS)z>:return: path or file descriptor of the underlying mapped file)rr.rs rr.zWindowCursor.path_or_fds{%%'''rct|jtrt d|jS)ze:return: path of the underlying mapped file :raise ValueError: if attached path is not a pathz>Path queried although mapping was applied to a file descriptor) isinstancerr.int ValueErrorrs rpathzWindowCursor.pathsH dk,,.. 4 4 _]^^ ^{%%'''rct|jtrt d|jS)z:return: file descriptor used to create the underlying mapping. **Note:** it is not required to be valid anymore :raise ValueError: if the mapping was not created by a file descriptorz@File descriptor queried although mapping was generated from path)rbrr.strrdrs rfdzWindowCursor.fdsH dk,,.. 4 4 a_`` `{%%'''r)NN)rrr)__name__ __module__ __qualname____doc__ __slots__rrr#r(rr6r9r;rJr*rOrQrTrVrXrCrEr5r@r=r.rerhr"rrr r s$$I* 2 2 2 &&&&PQQQ"""((('''+++ 888  aaa'''(((((((((((rr ceZdZdZgdZeZeZe Z e Z dZ ddejfdZdZdZdZd Zd Zd Zd Zd ZdZdZdZdS)r aProvides a manager which will produce single size cursors that are allowed to always map the whole file. Clients must be written to specifically know that they are accessing their data through a StaticWindowMapManager, as they otherwise have to deal with their window size. These clients would have to use a SlidingWindowMapBuffer to hide this fact. This type will always use a maximum window size, and optimize certain methods to accommodate this fact)r, _window_size_max_memory_size_max_handle_count _memory_size _handle_countirct|_||_||_||_d|_d|_|dkr!d}trd}||jz|_|dkr#d}trd}||jz|_dSdS)ainitialize the manager with the given parameters. :param window_size: if -1, a default window size will be chosen depending on the operating system's architecture. It will internally be quantified to a multiple of the page size If 0, the window may have any size, which basically results in mapping the whole file at one :param max_memory_size: maximum amount of memory we may map at once before releasing mapped regions. If 0, a viable default will be set depending on the system's architecture. It is a soft limit that is tried to be kept, but nothing bad happens if we have to over-allocate :param max_open_handles: if not maxint, limit the amount of open file handles to the given number. Otherwise the amount is only limited by the system itself. If a system or soft limit is hit, the manager will free as many handles as possibler@ii N) dictr,rorprqrrrsr _MB_in_bytes)rr?max_memory_sizemax_open_handlescoeffs rrzStaticWindowMapManager.__init__ sff ' /!1 ??E{{  %(9 9D  a  E{{ $)D,=$=D ! ! ! rcd}|dks|j|z|jkrd}d}|jD]5}|D]0}|dkr||j|jkr|}|}16|n{|dz }|||=|d|xj|zc_|xj dzc_ |dk|j|z|jk|S)amUnmap the region which was least-recently used and has no client :param size: size of the region we want to map next (assuming its not already mapped partially or full if 0, we try to free any available region :return: Amount of freed regions .. Note:: We don't raise exceptions anymore, in order to keep the system working, allowing temporary overallocation. If the system runs out of memory, it will tell. .. TODO:: implement a case where all unusued regions are discarded efficiently. Currently its only brute force rNrrL) rrrpr,values client_count_ucindexr3rErs)rrE num_found lru_regionlru_listrr5s r_collect_lru_regionz*StaticWindowMapManager._collect_lru_region/s0 qyyd/$69NNNJH;--// + +%++F++--22'/6: 3N3N%+ #* +! NI 334  - -b 1 1 1   !2!2 2     ! #  -qyyd/$69NNN0rcD|j|z|jkr||d}|rt|dksJ|d}n ||dt j|}nA#t$r4|r|d| ||||dcYSwxYw|xj dz c_ |xj| z c_| || |sJ|S)zUtilty to create a new region - for more information on the parameters, see MapCursor.use_region. :param a: A regions (a)rray :return: The newly created regionNrrT)rrrprr+ MapRegionClsr.sysmaxsize ExceptionrArsrEappendr@)rarDrErF is_recursivers rrAz%StaticWindowMapManager._obtain_regionXsJ  t #d&; ; ;  $ $T * * *   q66Q;;;;!AA I%%allnnaeLL I I I  ((+++**1fdE4HHHHH I   ! #      )   HHQKKK~~f%%%%%s 4B;B?>B?c|j|}|||}||j|<|||S)a :return: a cursor pointing to the given path or file descriptor. It can be used to map new regions of the file into memory **Note:** if a file descriptor is given, it is assumed to be open and valid, but may be closed afterwards. To refer to the same file, you may reuse your existing file descriptor, but keep in mind that new windows can only be mapped as long as it stays valid. This is why the using actual file paths are preferred unless you plan to keep the file descriptor open. **Note:** file descriptors are problematic as they are not necessarily unique, as two different files opened and closed in succession might have the same file descriptor id. **Note:** Using file descriptors directly is faster once new windows are mapped as it prevents the file to be opened again just for the purpose of mapping it.)r,getMapRegionListClsWindowCursorCls)rr.rs r make_cursorz"StaticWindowMapManager.make_cursorsQ +//*-- ?++J77G&-DK ###D'222rc,|dS)z]Collect all available free-to-collect mapped regions :return: Amount of freed handlesr)rrs rcollectzStaticWindowMapManager.collects''***rc|jS)zO:return: amount of file handles in use. Each mapped region uses one file handle)rsrs rnum_file_handlesz'StaticWindowMapManager.num_file_handless !!rchtdd|jDdS)z$Amount of opened files in the systemc ||zSrr")xys rz7StaticWindowMapManager.num_open_files..s 1q5rc3@K|]}t|dkdVdS)rrN)r+).0rlists r z8StaticWindowMapManager.num_open_files..s7*a*aRUV[R\R\_`R`R`1R`R`R`R`*a*arr)rr,r|rs rnum_open_filesz%StaticWindowMapManager.num_open_filess6((*a*a$+:L:L:N:N*a*a*acdeeerc|jS)z8:return: size of each window when allocating new regions)rors rr?z"StaticWindowMapManager.window_size   rc|jS)z2:return: amount of bytes currently mapped in total)rrrs rmapped_memory_sizez)StaticWindowMapManager.mapped_memory_sizerrc|jS)z6:return: maximium amount of handles we may have opened)rqrs rmax_file_handlesz'StaticWindowMapManager.max_file_handless %%rc|jS)z1:return: maximum amount of memory we may allocate)rprs rmax_mapped_memory_sizez-StaticWindowMapManager.max_mapped_memory_sizes $$rctjdkrdSd}|jD]8\}}||r|D]}||dz }9|S)aONLY AVAILABLE ON WINDOWS On windows removing files is not allowed if anybody still has it opened. If this process is ourselves, and if the whole process uses this memory manager (as far as the parent framework is concerned) we can enforce closing all memory maps whose path matches the given base path to allow the respective operation after all. The respective system must NOT access the closed memory regions anymore ! This really may only be used if you know that the items which keep the cursors alive will not be using it anymore. They need to be recreated ! :return: Amount of closed handles **Note:** does nothing on non-windows platformswin32Nrr)rplatformr,items startswithrelease)r base_path num_closedrerr5s rforce_map_handle_removal_winz3StaticWindowMapManager.force_map_handle_removal_wins <7 " " F ;,,.. $ $KD%y)) $#$$FNN$$$!OJJrN)rirjrkrlrmrrr MapWindowClsrrr rrwrrrrrArrrrr?rrrrr"rrr r s  I%LL"OL#$a#+>>>>H'''R$$$R333.+++ """fff!!!!!!&&&%%%rr cNeZdZdZeZddejffd ZdZ xZ S)r aMaintains a list of ranges of mapped memory regions in one or more files and allows to easily obtain additional regions assuring there is no overlap. Once a certain memory limit is reached globally, or if there cannot be more open file handles which result from each mmap call, the least recently used, and currently unused mapped regions are unloaded automatically. **Note:** currently not thread-safe ! **Note:** in the current implementation, we will automatically unload windows if we either cannot create more memory maps (as the open file handles limit is hit) or if we have allocated more than a safe amount of memory already, which would possibly cause memory allocations to fail as our address space is full.rLrcNt|||dS)z%Adjusts the default window size to -1N)superr)rr?rxry __class__s rrz SlidingWindowMapManager.__init__s& o7GHHHHHrcd}d}t|}||krM||zdz} || j} | |kr*|| |r || }n| dz}n| }||kM||j} |dd} |||} ||d} |j| z|jkr|| d}t|}|dkr|dj|krd}n&|}t|D]\}}|j|kr|}n|dkr#|r |j ||} nI||kr |j ||} |j ||dz } | | | | | | | | | jkr| j| jz | _ |j|jkrt&||| j| j|}nA#t&$r4|r|d|||||dcYSwxYw|xjdz c_|xj|z c_||||S)NrrT)r+rBr@rorr=rrrpr enumerate from_regionextend_left_toextend_right_toalignrCr^rErsrqrrr.rAinsert)rrrDrErFrrlohimidr^r?leftright insert_pos len_regionsir5s rrAz&SlidingWindowMapManager._obtain_regions?   VV2gg7q.CC&)Cf}}S6&&v..#A1W2gg 9+K$$Q**D##FD11C%%akkmmQ77E  ;.1FFF((555Ja&&KaQ47f$$!"J) !*1IAvy6))%& *QI -99!J-HHE,, -99!J-HHE(44QzA~5FGG   t[ 1 1 1   { 3 3 3 IIKKK{{}}uy(( 9sw. I%)???#O%%allnncgsxOO I I I  ((+++**1fdE4HHHHH I   ! #      )   HHZ # # #s"A I..;J,+J,) rirjrkrltuplermrrrrA __classcell__)rs@rr r sy  I#%q3;IIIIIIaaaaaaarr ) rlutilrrrrr functoolsr__all__r r r r"rrrsrr  O O O U(U(U(U(U(U(U(U(tffffffffTvvvvv4vvvvvr