e< dZddlZddlZddlZddlZddlZddlZddlmcm Z ddl m Z ddl mZddlmZmZddlmZddlmZmZmZmZmZmZmZddlmZmZdd lmZddlZdd l m!Z!dd l"m#Z#dd l$m%Z%dd l&m'Z'm(Z(ddl)m*Z*ddl+m,Z,m-Z-m.Z.ddl)m/Z/ddl0m1Z1ddl2m3Z3ej4dZ5e dddgZ6de7de6fdZ8dee7fdZ9dee7fdZ:dCdZ;dDde7d ed$e7dd%fd&Z?de7fd'Z@dEd)e7de7fd*ZAde7fd+ZBd,eCdeDfd-ZEd.e7dee7fd/ZFdeZQdBZRdS)Hz> 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_description)get_kmodlve_module_version)is_cl_solo_edition is_containerget_cl_edition_readable)get_rhn_systemid_value) sentry_dsn)SSAErrorutilsURL domain_nameuri_pathurlreturnct|}|jr d|jnd}|jr |j|nd}t|jdd|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) ?/zwww.)rquerypathr netlocreplace)r# fragmentsqsuris I/opt/cloudlinux/venv/lib64/python3.11/site-packages/ssa/internal/utils.py url_splitr12sl  I"+/ 9 Y_   rB%.^ s 4 5 55r2c tdS)z#Get version of alt-php-xray packagez/usr/share/alt-php-xray/versionr4r6r2r0 xray_versionr9Bs 8 9 99r2cdtdtdtfd}dfd}d}dd }tpd }ttjtj }t | }tjt||||g tj 5}d|i|_ ||n#t$rYnwxYwddddS#1swxYwYdS)u Initialize Sentry client shutdown_timeout=0 disables Atexit integration as stated in docs: 'it’s easier to disable it by setting the shutdown_timeout to 0' https://docs.sentry.io/platforms/python/default-integrations/#atexit On the other hand, docs say, that 'Setting this value too low will most likely cause problems for sending events from command line applications' https://docs.sentry.io/error-reporting/configuration/?platform=python#shutdown-timeout eventhintr$c@|dddi|S)z Add extra data into sentry event :param event: original event :param hint: additional data caught :return: updated event extraz ssa.versionz 0.4-3.el7)update)r;r<s r0add_infozsentry_init..add_infoSs& g}k:;;; r2c 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 r0 try_get_ipzsentry_init..try_get_ip]s 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_ipiprJs r0get_ipzsentry_init..get_iplsZ /08X2FF !+   HgHg..B   {r2c \t}|r|dnd}|r|dnd}dtpdfd|fd|fdtjfdt d fd t fd t d ff}|D] }|j| dS) Nversionnamez alt-php-xrayUNKNOWNzControl Panel NamezControl Panel VersionkernelzCloudLinux version os_releasezCloudlinux edition Architecture architecture)rgetr9platformreleaserrset_tag) sentry_scopecp_description cp_versioncp_nametagstags r0set_tagszsentry_init..set_tagsxs+--6DN^'' 222$ 0>H.$$V,,,D!<9=%w/(*58+--.%'=l'K'KL%'>'@'@A!7!G!GH J ' 'C L # & & & ' 'r2NcdSNr6)pendingtimeouts r0nopezsentry_init..nopesr2zalt-php-ssa@0.4-3.el7)level event_level)callback)dsn before_sendr[ integrations ip_addressr$N) dictr7rloggingINFOWARNINGr sentry_sdkinitrconfigure_scopeuserrD) r@rPrcrhssa_versentry_logging silent_atexitscoperJs @r0 sentry_initr}GsDT 6 6 6     '''"-,,,mm66G'gl4;OEEEN%t444MO #"0-!@BBBB  # % %"FFHH-   HUOOOO    D  s6!C4 C?C C  C C  CC!$C!Ffnameas_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)filenameriformatdatefmtiz$No logging configuration applied: %sN) rr basicConfigrsoschmodPermissionErrorOSErrorrElogERRORstr)r~res r0set_logging_into_filers U',#<$: < < < <  HUE " " " "    D   H>7==',9q66         s8"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) r}rrmakedirsr*dirnamerDrEwarningr)rrs r0configure_loggingrs MMMW%%-  K00 1 1 1 1    NN7Q @ @ @22222 ($??? Ns1A B(B  B sock_locationz socket objectcttjdd}|dkrdt 5t t }|||dddn #1swxYwYn/tdt t}||S)z Create world-writable socket in given sock_location or reuse existing one :param sock_location: socket address :return: socket object LISTEN_FDSrN) intrenvironrYumask_0rr bindlistenr r )rrsockobjs r0 create_socketrsRZ^^L!4455JQ YY  WooG LL ' ' ' NN                   G[11 Ns>B  BBcttjtdz }|dS)zC Returns date of previous day in a format "day.month.year" r)days%d.%m.%Y)rtodayrstrftime) yesterdays r0previous_day_daters3 ya0000I   j ) ))r2rdatestrcltj||}|dS)z+ Convert date to format YYYY-mm-dd z%Y-%m-%d)datetimestrptimer)r formatstr_dates r0 format_daters.   & &w : :E >>* % %%r2c 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/string system_idNzID-z Failed to retrieve system_id: %s)ETparsegetrootfindtextrurwr\lstripr ParseErrorrErr)treerootwhole_idr|rs r0 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 r0 duration_castrs! (&11 2 22r2filepathc& 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_filerRs r0r5r5s (^^ ,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)r9r TypeErrorAttributeError)version_numbers r0is_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 rBConnectionErrorr)user_agent_sockrIs r0is_xray_user_agent_activers>, - -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) rrLVErErFrwriterr)rfrs r0switch_schedstatsr/sD &gk 2 2 KK*G444% 5D #"# GGG-DD . . . KK " " " # # # # # # # # # # # # # # # # # # %%% >SVV % % % % % % % % %%s;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 r0$is_io_throttling_detection_availablerCs] $H--%h//-//LC"<1ABBB 5779K L LLr2ctjd}tj} ||d}n#t $rYdSwxYw|S)zO Get kernel version in the form of "major-minor" from current platform zlve([.0-9]*).elrz0.0.0)recompilerZr[searchgroupr)patternr[ version_nums r0rrPspj+,,G  GnnW--33A66 ww s(A A A  first_versionsecond_versioncz t||kS#t$r}td|d|dd}~wwxYw)zE Comparing two versions using the greater or equal operator. zAUnable to compare required versions: unexpected versions format "z" and ""N)rrr)rrrs r0rr]skyM**n<< yyy wP] w wft w w wyy yys :5:c^tdstrdStS)zR General check of kernel support (IO throttling availability is required) T)skip_jwt_check)rrrr6r2r0is_kernel_version_supportedrhs3...,..t / 1 11r2maskc#bKtj|}dVtj|dS)z, Context manager for dropping umask N)rumask)rprevs r0rrts/ 8D>>D EEEHTNNNNNr2rT 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|tddV||kr/tj |t d|||kr/tj|t d||tj|dSdS)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_gidrsetegidrEdebuggetegidrseteuidgeteuid) rr target_pathr with_checkprev_uidprev_gid stat_infors r0set_privilegesr~s"y{{Hy{{HGK((    !JJ")J  !JJ")J x~~: : . ;;;  J"*,,*44HJJ J: : . ;;;  J"*,,*44:%% 8$$$HJJ J EEE: 8 /:::: 8 /:::  s? A Ac2Gdd}||S)NceZdZdZdZdZdS)singleton..__Singletonzm A singleton wrapper class. Its instances would be created for each decorated class. c"||_d|_dSre)_wrapped _instance)self_clss r0__init__z'singleton..__Singleton.__init__s DM!DNNNr2cP|jts|j|i||_|jS)z,Returns a single instance of decorated class)rIS_SINGLETON_ENABLEDr)rargskwargss r0__call__z'singleton..__Singleton.__call__s0~%-A%!.!?!?!?> !r2N)__name__ __module__ __qualname____doc__rrr6r2r0 __Singletonrs<   " " " " " " " "r2r$r6)some_clsr$s r0 singletonr&s<"""""""" ;x  r2rp)F)r)r)NNrNT)Sr#rrrrrrZrxml.etree.ElementTreeetree ElementTreer collectionsr contextlibrrrdistutils.versionrrr r r r r rtypingrr urllib.parserrusentry_sdk.integrations.atexitrsentry_sdk.integrations.loggingrclcommon.constrclcommon.cpapirrclcommon.utilsrclcommon.lib.cleditionrrrr constantsr exceptionsr getLoggerrEr rr1r7r9r}boolrrrrrrrrrr5rrrrrrrrrrrr&r6r2r0r9sf   """""""""""""""%%%%%%$$$$$$$$******""""""""!!!!!!<<<<<<>>>>>>""""""IIIIIIII555555 211111!!!!!!  7 # #j 344 :3 :3 : : : :6Xc]6666:hsm:::: RRRRj(ss"&*3****&&&s&&&& CS C C C C 3C3E33337#7(3-7777 4    4 d     %t%%%%%( Md M M M M     ysyE#|BS