Mj @ DdZddlZddlZddlZddlZddlZddlZddlmcm Z ddl m Z ddl mZddlmZmZddlmZddlmZmZmZmZmZmZmZddlmZmZdd lmZddlZdd l m!Z!dd l"m#Z#dd l$m%Z%dd l&m'Z'm(Z(m)Z)m*Z*ddl+m,Z,m-Z-ddl.m/Z/ddl0m1Z1ddl+m2Z2ddl3m4Z4ddl5m6Z6ej7dZ8e dddgZ9de:de:fdZ;de:de9fdZdFdZ?dGd!e:d"e@de:fd#ZAd$e:de:fd%ZBdHd'e:d(eCdefd)ZDde:fd*ZEdId,e:de:fd-ZFde:fd.ZGd/eCdeHfd0ZId1e:dee:fd2ZJde@fd3ZKde@fd4ZLde@fd5ZMd6e@ddfd7ZNde@fd8ZOde:fd9ZPd:e:d;ee:efde@fd<ZQd=ZRedJd>eCddfd?ZSe dKdBeCdCeCd>eCddfdDZTdAZUdEZVdS)Lz> This module contains helpful utility functions for SSA Agent N) namedtuple)contextmanager)date timedelta) LooseVersion)socketfromfdAF_UNIX SOCK_STREAMAF_INETAF_INET6 SOCK_DGRAM)OptionalUnion)urlparse)AtexitIntegration)LoggingIntegration)Feature)is_panel_feature_supportedget_cp_descriptionis_throttling_supportedis_wp2_environment)get_kmodlve_module_version get_username)get_cl_edition_readable) get_hostname)get_rhn_systemid_value) sentry_dsn)SSAErrorutilsURL domain_nameuri_pathurlreturncRt|jddS)u The domain string the request processor stores as RequestResult.domain. This is the single source of truth for a URL's domain attribution: it operates on the raw netloc and removes every 'www.' substring, exactly as the stored metric is keyed. The authorizer MUST derive its decision from this same value (see SimpleAgent._authorize_sender) — any divergence re-opens cross-tenant metric spoofing. zwww.)rnetlocreplace)r%s I/opt/cloudlinux/venv/lib64/python3.11/site-packages/ssa/internal/utils.pycanonical_stored_domainr,0s# C==  ' ' 3 33ct|}|jr d|jnd}|jr |j|nd}tt ||S)z Split URL into domain_name and uripath including query string :param url: URL of format protocol://domain/path;parameters?query#fragment :return: namedtuple URL(domain_name, uripath) ?r(/)rquerypathr"r,)r% fragmentsqsuris r+ url_splitr6<sb  I"+/ 9 Y_   rB%.^ .add_info_s& g}l;<<< r-c t|t5}||df|dcdddS#1swxYwYdS#t$rt dYdSwxYw)aI address_family - we can choose constants represent the address (and protocol) families (AF_INET for ipv4 and AF_INET6 for ipv6) private_ip - specify some private ip address. For instance: ipv4 -> 10.255.255.255 or ipv6 -> fc00:: rrNzCannot retrieve IP address)rrconnect getsockname Exceptionloggerinfo)address_family private_ipss r+ try_get_ipzsentry_init..try_get_ipis 6 33 *q :q/***}}q) * * * * * * * * * * * * * * * * * * 6 6 6 KK4 5 5 5 5 5 5 6s4A"1A A"AA"AA""$B  B c`tdftdff}|D]\}}||}|r|cSdS)zq We are trying to get an IPv4 or IPv6 address. In case of failure we'll return 127.0.0.1 z10.255.255.255zfc00::z 127.0.0.1)r r ) ipversionsaddr_fampriv_ipiprNs r+get_ipzsentry_init..get_ipxsZ /08X2FF !+   HgHg..B   {r-c t}|r|dnd}|r|dnd}trdnd}dtpdfd|fd|fd|fd t jfd t d fd tfd t dfdfdtff }|D] }|j | dS)NversionnameWP2z alt-php-xrayUNKNOWNzControl Panel NamezControl Panel VersionzControl Panel ProductkernelzCloudLinux version os_releasezCloudlinux edition Architecture architecture ip_addressusername) rgetrr=platformreleaserrrset_tag) sentry_scopecp_description cp_versioncp_name cp_producttagstagrTs r+set_tagszsentry_init..set_tagss+--6DN^'' 222$ 0>H.$$V,,,D022.nopes r-zalt-php-ssa@0.4-30.el8)level event_level)callbacki')dsn before_sendrbmax_value_length integrationsid system_idr&N)dictr;rloggingINFOWARNINGr sentry_sdkinitrconfigure_scoperrruserrH) rDrkrpssa_versentry_logging silent_atexitscoperTrNs @@r+ sentry_initrSsDT 6 6 6     '''''.    mm77G'glXXXN%t444MO $m4   # % %2;??o6688o|~~oamaoaop   HUOOOO    D  s6%=D # C/.D / C<9D ;C<<D  DDFfnameas_errorcL tj|tjdd tj|dn#t $rYnwxYw|S#t $rL}t|r tj n tjdt|Yd}~dSd}~wwxYw)zz Try to configure logging into given fname If as_error True, log the exception as ERROR, otherwise -- as INFO z%(asctime)s %(message)sz%m/%d/%Y %I:%M:%S %p)filenamerqformatdatefmtiz$No logging configuration applied: %sN) r| basicConfigr}oschmodPermissionErrorOSErrorrIlogERRORstr)rres r+set_logging_into_filers p',7PZp      HUE " " " "    D  ppp H>7==',@fhklmhnhnooooooooops8"A ;A AA AA B#ABB#lognamecHtt| tjtj|n@#t $r3}tdt|Yd}~dSd}~wwxYwt|d}|S)zP Configure logging :param logname: path to log :return: logpath NzFailed to create logdir %sr(T)r) rrrmakedirsr2dirnamerHrIwarningr)rrs r+configure_loggingrs MMMW%%-  K00 1 1 1 1    NN7Q @ @ @22222 ($??? Ns1A B(B  B sock_locationbacklogcttjdd}|dkrft d5t t }||||dddn #1swxYwYn0tdt t}|||S)a  Create socket in given sock_location with restricted permissions or reuse existing one :param sock_location: socket address :param backlog: maximum number of queued connections (default 2048 for high-traffic servers) :return: socket object LISTEN_FDSrIN) intrenvironr`umask_0rr bindlistenr r )rrrsockobjs r+ create_socketrsRZ^^L!4455JQ U^^ $ $WooG LL ' ' ' NN7 # # # $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ G[11w Ns?BBBcttjtdz }|dS)zC Returns date of previous day in a format "day.month.year" r)days%d.%m.%Y)rtodayrstrftime) yesterdays r+previous_day_daters3 ya0000I   j ) ))r-rdatestrcltj||}|dS)z+ Convert date to format YYYY-mm-dd z%Y-%m-%d)datetimestrptimer)r formatstr_dates r+ format_daters.   & &w : :E >>* % %%r-c tjd}|}|dj}t j5}|d|dddn #1swxYwY|dS#ttj f$r3}t dt|Yd}~dSd}~wwxYw)ze Obtain system ID from /etc/sysconfig/rhn/systemid :return: system ID without ID- prefix z/etc/sysconfig/rhn/systemidz(.//member[name='system_id']/value/stringryNzID-z Failed to retrieve system_id: %s)ETparsegetrootfindtextrrrclstripr ParseErrorrIrr)treerootwhole_idrrs r+ read_sys_idrs Cx566||~~99GHHM  ' ) ) 1U MM+x 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1u%%% R] #CCC93q66BBBBBBBBBCs<ABA:. B:A>>BA>BC#0(CC#durationcBtt|dz dS)zQ Cast duration from microseconds to seconds leaving 2 digits after point i@Bz0.2f)floatr)rs r+ duration_castrs! 7*F33 4 44r-filepathc& t|5}|}dddn #1swxYwYn#t$rYdSwxYwd|dddpdS)zDGet version of package from file. alt-php-ssa/alt-php-xray supportedN.z0.0-0)openreadstriprjoinsplit)rv_filerVs r+r9r9s (^^ ,vkkmm))++G , , , , , , , , , , , , , , ,  88GMM#&&rr* + + 6w6s3A'A AAA A A AAct}|dS t|tdkS#ttf$rYdSwxYw)zb Check version of alt-php-xray package. Autotracing in X-Ray is supported since 0.4-1 NFz0.4-1)r=r TypeErrorAttributeError)version_numbers r+is_xray_version_supportedrs_ "^^NuN++|G/D/DDD ~ &uus4A A cd}ttt5} ||n##tt f$rYddddSwxYw dddn #1swxYwYdS)z Check if User Agent is listeningz$/opt/alt/php-xray/run/xray-user.sockNFT)rr r rFConnectionErrorr)user_agent_sockrMs r+is_xray_user_agent_activer)s>, - -t X(# . . /*z(())Q. / / / / / / / / / / / / / / / / / / 9uus4A9%A, A9,A00A93A04A99B  B enabledcttjsdStd| t ddd5}||rdndtd ddddS#1swxYwYdS#t$r4}td |t|Yd}~dSd}~wwxYw) zb Switch on/off throttle statistics gathering by kmodlve :param enabled: True or False NzSwitching schedstats: %sz!/proc/sys/kernel/sched_schedstatswbr)mode buffering10zDone OKz(Failed to set sched_schedstats to %s: %s) rrLVErIrJrwriterr)rfrs r+switch_schedstatsrDs/ &gk 2 2 KK*G444Q 5DA N N N #RS GGG-DD . . . KK " " " # # # # # # # # # # # # # # # # # # QQQ >QPPPPPPPPPQs;B 4B > B BBBB C")CCctd}td}t}|rt||Stt|S)z Check kmodlve module version or kernel version in order to determine if it provides the detection of IO throttling z2.0-23z1.5.58)rrcompare_versions_geextract_kernel_version)kmod_min_versionkernel_min_version kmod_currents r+$is_io_throttling_detection_availablerVs] $H--%h//-//LC"<1ABBB 5779K L LLr-ctjd}tj} ||d}n#t $rYdSwxYw|S)zO Get kernel version in the form of "major-minor" from current platform zlve([0-9]+(\.[0-9]+)+)\.elrz0.0.0)recompilerarbsearchgroupr)patternrb version_nums r+rrcspj677G  GnnW--33A66 ww s(A A A  first_versionsecond_versioncr t||kS#t$rtd|d|dwxYw)zE Comparing two versions using the greater or equal operator. zAUnable to compare required versions: unexpected versions format "z" and "")rrr )rrs r+rrps_ M**n<<     wP] w wft w w w    s!6c>tsdStS)zR General check of kernel support (IO throttling availability is required) T)rrr:r-r+is_kernel_version_supportedr|s# # $ $t / 1 11r-maskc#Ktj|} dVtj|dS#tj|wxYw)z, Context manager for dropping umask N)rumask)rprevs r+rrsF 8D>>D  s 2ArT target_uid target_gidc#Ktj}tj} tj|}n#t$rd}YnwxYw| ||}n|j}| ||}n|j}|tj|}||krWtj|t d||r&tj |krtd||krqtj |t d||r@tj|kr)||krtj|td dV||kr/tj |t d|||kr/tj|t d||tj|dSdS#||kr/tj |t d|||kr/tj|t d||tj|wwxYw)aH Context manager to drop privileges during some operation and then restore them back. If target_uid or target_gid are given, use input values. Otherwise, stat target_uid and target_gid from given target_path. If no target_path given, use current directory. Use mask if given. :param target_uid: uid to set :param target_gid: gid to set :param target_path: directory or file to stat for privileges, default -- current directory :param mask: umask to use :param with_check: check the result of switching privileges NzDropped GID privs to %sz6Unable to execute required operation: permission issuezDropped UID privs to %szRestored UID privs to %szRestored GID privs to %s)rgetuidgetgidstatrst_uidst_gidrsetegidrIdebuggetegidr seteuidgeteuid) r r  target_pathr with_checkprev_uidprev_gid stat_infor s r+set_privilegesrs{$y{{Hy{{HGK((    !JJ")J  !JJ")J x~~: : . ;;;  U"*,,*44STT T: : . ;;;  U"*,,*44:%% 8$$$STT T   z ! ! Jx LL3X > > > z ! ! Jx LL3X > > >   HTNNNNN   z ! ! Jx LL3X > > > z ! ! Jx LL3X > > >   HTNNNN s? A AG BI#c2Gdd}||S)NceZdZdZdZdZdS)singleton..__Singletonzm A singleton wrapper class. Its instances would be created for each decorated class. c"||_d|_dSrm)_wrapped _instance)self_clss r+__init__z'singleton..__Singleton.__init__s DM!DNNNr-cP|jts|j|i||_|jS)z,Returns a single instance of decorated class)r"IS_SINGLETON_ENABLEDr!)r#argskwargss r+__call__z'singleton..__Singleton.__call__s0~%-A%!.!?!?!?> !r-N)__name__ __module__ __qualname____doc__r%r*r:r-r+ __Singletonrs<   " " " " " " " "r-r/r:)some_clsr/s r+ singletonr1s<"""""""" ;x  r-rz)F)r)r)r)NNrNT)Wr.rrr|rrarxml.etree.ElementTreeetree ElementTreer collectionsr contextlibrrrdistutils.versionrrr r r r r rtypingrr urllib.parserrsentry_sdk.integrations.atexitrsentry_sdk.integrations.loggingrclcommon.constrclcommon.cpapirrrrclcommon.utilsrrclcommon.lib.cleditionrclcommon.lib.networkrr constantsr exceptionsr getLoggerrIr"rr,r6r;r=rboolrrrrrrrrrr9rrrrrrrrrrr'r1r:r-r+rEsx   """""""""""""""%%%%%%$$$$$$$$******VVVVVVVVVVVVVVVVVV""""""""!!!!!!<<<<<<>>>>>>""""""vvvvvvvvvvvvCCCCCCCC::::::------111111!!!!!!  7 # #j 344 4 4 4 4 4 4 23 23 2 2 2 26Xc]6666 :hsm:::: [[[[|pppppppp$ss"sf(*3****&&&s&&&& CS C C C C 5C5E55557#7(3-7777 4    4 d     QtQQQQQ$ Md M M M M       s  E#|BS